Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Accept only array of specific class

Tags:

arrays

php

class

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

like image 468
Eliya Cohen Avatar asked Aug 08 '16 12:08

Eliya Cohen


1 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

like image 165
Machavity Avatar answered Nov 08 '22 20:11

Machavity