PHP - Accept only array of specific class -
let's have product
class, how can tell php want accept array of product
?
in other words, there way method?:
private function method(product[] $products) { // ... }
i thought doing this:
private function validate($products) { foreach ($products $product) if (!is_a($product, 'product') return false; // ... }
it work, don't idea of adding bunch of lines make sure it's "product[]
".
you can type hint whatever container is. have
private function method(array $products)
php can validate argument in given type hint, , not argument might contain.
the best way validate array loop said, make slight change
private function validate(array $products) { foreach($products $product) if (!($product instanceof product)) return false; }
the benefit here avoid overhead of function call
another idea make wrapper class
class product_wrapper { /** @var array */ protected $products = array(); public function addproduct(product $product) { $this->products[] = $product; } public function getproducts() { return $this->products; } }
this way, wrapper cannot contain except instances of product
Comments
Post a Comment