8

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

1
  • Since there are no typed arrays, there is nothing like this either. You could perhaps implement it if you create your own class for a list of products first. Then that class could be used in the type hinting parameter, and that class itself would have to ensure that only products can be added to its internal data array. Commented Aug 8, 2016 at 12:28

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your answer. I was kinda hoping from PHP to implement something like that :\ If there won't be a better answer, I'll mark this as the answer. Again, Thank you :)
@EliyaCohen I did have one more thought. Check my edit

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.