Jason Basanese
Jason Basanese

Reputation: 720

PHP - How to assign object variables to function variables automatically?

Below is a fragment of one of my functions, but I figured this seemed redundant and thus wanted to avoid it.

 function cellMaker($cell){
        $label= $cell['label'];
        $type= $cell['type'];
        $return= $cell['return'];
        $size= $cell['size'];
        $name= $cell['name'];
        $value= $cell['value'];
         ........

The reason I am doing this is to avoid having to fill in nulls with the function if I only need to pass two of the parameters, like just label and type and value. That would look like cellMaker('how?', 'text' null, null, null, 'because');

Rather I only would need to do cellMaker(["label" => "how?", "type"=> "text", "value" => "because"]) which saves me from having to remember the order the variables are defined in the function and from having to deal with unnecessary variables. However I also do not want to have to type $cell['variable'] rather than $variable each time.

Is there a way to automatically assign all variables of an object to function variables of the same name?

Upvotes: 0

Views: 54

Answers (1)

wazelin
wazelin

Reputation: 751

You may use extract function to get separate variables from an array.

$array = ["label" => "how?", "type"=> "text", "value" => "because"];
extract($array);

This will give you three variables named after keys in the array containing corresponding values. Be warned though. It may become rather unpredictable. You wouldn't know for sure what kind of keys there may be in the input array.

Upvotes: 1

Related Questions