简体   繁体   中英

PHP - Accept only array of specific 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[] ".

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM