Java-like Collections in PHP

后端 未结 7 1348
情话喂你
情话喂你 2021-01-04 01:48

I\'m learning PHP5 (last time I checked PHP was in PHP4 days) and I\'m glad to see that PHP5 OO is more Java-alike than the PHP4 one but there\'s still an issue that makes m

7条回答
  •  情话喂你
    2021-01-04 02:34

    I sometimes use this really simple implementation to give me a rough and ready collection.

    Normally the main requirement of a collection is enforcing a group of one type of object, you just have to setup a basic class with a constructor to implement it.

    class SomeObjectCollection {
    
       /**
        * @var SomeObject[]
        */
       private $collection = array();
    
       /** 
        * @param SomeObject $object1
        * @param SomeObject $_ [optional]
        */
       function __construct(SomeObject $object1 = null, SomeObject $_ = null) 
       {
           foreach (func_get_args() as $index => $arg) {
               if(! $arg instanceof SomeObject) throw new \RuntimeException('All arguments must be of type SomeObject');
               $this->collection[] = $arg;
           }
       }
    
       /**
        * @return SomeObject[]
        */
       public function getAll()
       {
           return $this->collection;
       }
    }
    

提交回复
热议问题