Re: Re: Simplest way of enforcing an array of instances of a specific class but treating the whole thing as an array.

From: Date: Thu, 24 Feb 2011 18:28:34 +0000
Subject: Re: Re: Simplest way of enforcing an array of instances of a specific class but treating the whole thing as an array.
References: 1 2  Groups: php.general 
Request: Send a blank email to php-general+get-311571@lists.php.net to get a copy of this message
If each array will contain a single type of object, but you need many of these arrays, each containing a different type of object, I recommend creating a generic "instances-of-class" array using ArrayObject. You can enforce the type in append(), offsetSet(), and exchangeArray() and then check the configured type in methods that want to enforce it. function drawMap(TypedArray $latLngs=null) { if ($latLngs && !$latLngs.containsOnly('LatLng')) { throw new InvalidArgumentException('$latLngs must contain only LatLngs'); } ... } I guess since there are only three methods to override it wouldn't be too painful to create a separate class for each type to get method declaration type hinting. If you aren't containing too many classes and you pass them around a lot, it may be worth it since you won't have to test the container inside the method at all. function drawMap(LatLngArray $latLngs=null) ... Looks like someone beat us to it: http://liamgraham.wordpress.com/2007/05/21/typesafe-arrays-for-php/ David

« previous php.general (#311571) next »