3

I would like to instanciate a class, that takes any number of consturctor params.

Lets say I have a class Man, that takes two arguments in constructor.

class Man
{
    protected $name;
    protected $age;

    public function __construct($name, $age)
    {
        $this->name = $name;
        $this->age = $age;
    }
}

Then I have params:

$params = array()
$params['name'] = 'Jack';
$params['age'] = 55;

And this is how I instanciate a class:

$jack = new Man($params['name'], $params['age']);

Now what I would like to achive is that params array can be of any size, 2, 3, 4, any, and class I would instanciate would have the same number of params.

So the only thing bothering me is how can I create variables automaticly? There is extract function but it returns the number of variables :(

I would need something this:

$jack = new Man($name, $age);

But this should be created automaticly. The script is only aware of the params array, and it needs to push all array values as variables.

The closest thing would be this:

$jack = new Man(extract($params));

But extract function returns number, and i need to create variables from array, and give them to the class constructor.

Edit:

I cant change the class Im building, my only goal is to construct that class, and pass variables it expects in constructor. So I have no power over the class Im building, my goal is to only instanciate that class, and gave her consturctor params. Those params are stored in $params array, but the class needs it as variables. Hope its easier to grasp what Im trying to achive.

Thanks

3
  • 6
    why not pass the array to the constructor? Commented Sep 2, 2012 at 19:31
  • Im trying building Dependency Injection Container, so that container would instanciate a class not built by me. And if that class expects 2 variables in constructor than I must put them there. So I can "tell" container that there is a class that needs 2 params in construct. And that those two params are in $params array. Now :) how would I push those variables that are in $params array, as variables. Commented Sep 2, 2012 at 19:39
  • 1
    Updated my answer to include a possible function to allow for you to extract the parameters without modifying the class. Commented Sep 3, 2012 at 0:24

6 Answers 6

1

You can do one of two things:

  1. Pass in an array of parameters:

    public function __construct(array $params) {}
    
  2. Use func_get_args() inside the function to get all of the arguments in the form of an associative array.

The first method is preferable, as it contains less "magic".

In order to call a function with an unknown set of arguments, when the arguments are in the form of an array you can use call_user_func_array().

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

Comments

1

I would pass the array to the constructor:

$jack = new Man($params);

and then handle the params in the constructor:

class Man
{
  public $Age;

  public function __construct( array $params )
  {
     foreach( $params as $key => $value ) {
       if( property_exists( $this, $key ) {
         $this->$key = $value;
       }
     }
  }
}

Comments

1

Yes, extract will return the number of variables but also creates the variables also. You would have to write the class so it takes the array as input then call extract from within the class. This will create the variables using the names set as the label for each element of the array.

--EDIT--

After seeing change to question I revised a more accurate answer.

--Example--

$params = array();  
$params['name'] = 'Jack';  
$params['age'] = 55;  

$jack = createMan($params);

//Function designed to extract correct parameters from $params

function createMan($params){

    extract($params);

    if(isset($name) && isset($age)){
        return new man($name, $age);
    }else{
        //What ever error logging and return null
        return null;
    }
}

Comments

0

What I needed was this:

ReflectionClass::newInstanceArgs

So the solution to my problem is this:

$reflection = new \ReflectionClass($class); 
return $reflection->newInstanceArgs($params);

Where $params is array with params, and $class is name of the class Im building.

Thanks for all the comments!

2 Comments

Please in the future, if you answer your own question mark it the accepted answer. That way if some one comes back to check, they won't waste time answering/editing their answer. Congrats on finding a solution.
Thanks RMDan, I'm forced to wait for 2 days before I can mark this answer as as accepted. :) Thanks for all the help!
-1

Iterate over your array, and set the properties of your class using the $obj->{$keyname} syntax.

public function __construct($params) {
    foreach($params as $key => $value) {
        $this->$key = $value;
    }
}

Comments

-1

this might help:

class man{
   public function __construct($params){
      foreach($params as $key=>$value){
       $this->$key=$value;
      }
   }
}

This way, array keys will be assigned as variables.

2 Comments

That's the same as my answer, which was 6 minutes earlier!
well i think typing takes a few minutes.

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.