I'm working on a school assignment in Php. I've come to a point where I want to store a group of objects (all instances of the same class) in a single object which I then return. At the moment I use arrays for this, but this has a couple of cons for me.
I know that in C# and Java there are specific classes and interfaces for this such as List
, Dictionary
and Map
.
Is there any way to create similar behavior in Php, by writing a class or maybe extending an existing one? (The most important aspect of this is checking/forcing the type of the elements being added)
What i want:
$collection = Series::getAll(); // Returns a Collection<Series>, currently returns an array
echo $collection->toJson(); // This is currently not possible, because it's an array
$anotherCollection = new Collection<Movie>(); // I realize Php doesn't support this syntax, but I want this behavior, the syntax can be different for all I care
While any object will do for typehinting, PHP provides some base classes with array-like capabilities you could extend to suit your needs, such as ArrayObject
: http://php.net/arrayobject
UPDATE: usage example
class A{}
class B{}
class CustomList extends ArrayObject{
protected $validType = 'A';
public function offsetSet($index, $val) {
if(! $val instanceof $this->validType) {
throw new \Exception('Cannot add item object of class '.get_class($val));
}
return parent::offsetSet($index, $val);
}
}
$list = new CustomList();
$a = new A();
$b = new B();
$list[] = $a; // this one is ok
$list[] = $b; // fails - throws exception
One could set the validType
property externally (making it public, or using a setter method), or extend the class and override the property in child instances.
Yes there is a way, as you said; by writing a simple class. You'll need to use type-hinting:
http://www.php.net/manual/en/language.oop5.typehinting.php
Many frameworks / libraries have their own solutions already, it might be worth checking them out:
http://www.doctrine-project.org/api/common/2.3/class-Doctrine.Common.Collections.ArrayCollection.html https://github.com/propelorm/Propel/blob/master/runtime/lib/collection/PropelCollection.php