PHP - Accept only array of specific class -


let's have product class, how can tell php want accept array of product?

in other words, there way method?:

private function method(product[] $products) {     // ... } 

i thought doing this:

private function validate($products) {     foreach ($products $product)         if (!is_a($product, 'product')             return false;      // ... } 

it work, don't idea of adding bunch of lines make sure it's "product[]".

you can type hint whatever container is. have

private function method(array $products) 

php can validate argument in given type hint, , not argument might contain.

the best way validate array loop said, make slight change

private function validate(array $products) {     foreach($products $product)         if (!($product instanceof product))             return false; } 

the benefit here avoid overhead of function call

another idea make 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, wrapper cannot contain except instances of product


Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -