Let's say I have a Product
Class, How can I tell PHP that I want to accept only Array of Product
?
In other words, Is there a way to do something like this method?:
private function method(Product[] $products)
{
// ...
}
I thought about doing something like this:
private function validate($products)
{
foreach ($products as $product)
if (!is_a($product, 'Product')
return false;
// ...
}
It could work, but I don't like this idea of adding a bunch of lines just to make sure it's a "Product[]
".
You can only type hint whatever the container is. So you would have to do
private function method(Array $products)
PHP can only validate the argument itself in a given type hint, and not anything the argument might contain.
The best way to validate the array is a loop as you said, but I would make a slight change
private function validate(Array $products)
{
foreach($products as $product)
if (!($product instanceof Product))
return false;
}
The benefit here is you avoid the overhead of a function call
Another idea would be to make a 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, your wrapper cannot contain anything except instances of Product
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With