Home » Php » PHP – Accept only array of specific class

PHP – Accept only array of specific class

Posted by: admin July 12, 2020 Leave a comment

Questions:

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[]“.

How to&Answers:

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