1

When Defining a constructor in a class I initially had something like:

public function __construct(MyClass $class){ ... }

However I wanted to be able to accept an array of MyClasses, how could you define this in your constructor?

Cheers

3 Answers 3

2

Not strictly typecasting, but will enforce what you're looking for.

public function __construct(array $classes){
        foreach($classes as $inst){
          if(!($inst instanceof ClassName)){
            trigger_error('Array of objects passed to constructor must contain instances of ClassName', E_USER_ERROR);
            }
            //perform actions
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

0

You can only specify one type this way.

So, either an object, instance of MyClass :

public function __construct(MyClass $class){ ... }

Or an array :

public function __construct(array $data){ ... }

But you cannot specify your method only accepts an array of MyClass -- which means you'll have to check by yourself what kind of data are into the array your receive, in the second case.

1 Comment

or nothing: public function __construct($class){ ... }
0

Cast $class as an array.

public function __construct($class = array()) { }

or

public function __construct(array $class) { } 

further:

foreach($class as $instance) { 
      if(!$instance instanceof MyClass) { return false; }
}

Comments

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.