php_nub_qq
php_nub_qq

Reputation: 16017

Pass array as function parameters for class constructor

How can I pass an array as constructor parameters in class instantiation?

abstract class Person {

    protected function __construct(){

    }

    public static final function __callStatic($name, $arguments){
        return new $name($arguments);
    }

}

class Mike extends Person {

    protected function __construct($age, $hobby){
        echo get_called_class().' is '.$age.' years old and likes '.$hobby;
    }
}


// =============================================

Person::Mike(15, 'golf');

This should output

Mike is 15 years old and likes golf

But I get second parameter missing in Mike's constructor, because both parameters from __callStatic are sent as array into $age. My question is how can I send them as parameters instead of array?

Upvotes: 2

Views: 880

Answers (3)

Schlaus
Schlaus

Reputation: 19182

Use call_user_func_array(), https://www.php.net/manual/en/function.call-user-func-array.php and a factory method:

class Mike extends Person {

    public static function instantiate($age, $hobby) {
        return new self($age, $hobby);
    }
    protected function __construct($age, $hobby){
        echo get_called_class().' is '.$age.' years old and likes '.$hobby;
    }
}

And then make a Mike like so:

abstract class Person {

    protected function __construct(){

    }

    public static final function __callStatic($name, $arguments){
        return call_user_func_array(array($name, 'instantiate'), $args);
    }

}

Upvotes: 1

Machavity
Machavity

Reputation: 31614

You're using the static scope resolutor wrong

Person::Mike(15, 'golf');

That would mean you have a static method Mike inside the class Person and you're calling it statically.

Instead, you want to instantiate Mike

$mike = new Mike(15, 'golf');

If you want to call static things from Person, because Mike extends it, Mike can also call it statically.

Mike::staticMethod($args);

Upvotes: 0

Jeff Lambert
Jeff Lambert

Reputation: 24661

You can use Reflection for this:

public static function __callStatic($name, $arguments){
    $reflector = new ReflectionClass($name);
    return $reflector->newInstanceArgs($arguments);
}

Upvotes: 2

Related Questions