Jump to content

why does __call pass arguments and also an empty array? PHP5.3


johnmerlino

Recommended Posts

In my view file, I instantiate User class and call two methods that have not been declared or initialized in the class:

 

$user = new Models\User();

$user->setFirstName('John');

$user->setLastName('Merlino');

 

echo $user->getFirstName() . " " . $user->getLastName();

 

However, I have two private members only available to instances:

protected $first_name;

protected $last_name;

 

Because I don't want to manually create privileged getters and setters for each of my private members, I use the call method:

 

public function __call($name,$args){

 

echo $name . "<br />";

echo $args . "<br />";

 

}

 

Because my methods were not initialized, the interpreter calls the __call method as a last option resort, and passes the name of the method in local variable $name and if exists the arguments passed into the method in local variable $args. Ok so that makes sense. However, when I echo the values of the two variables, I see a blank array created:

 

setFirstName

Array

setLastName

Array

getFirstName

Array

getLastName

Array

 

See everytime I call it, there's an array being created. I don't see the purpose of this.

 

 

Also how often do you use __call() in your php applications, specifically when using MVC?

 

Thanks for response.

The best guess that I have as to why the list of arguments provided by __call is an array is a matter on convenience. The arity of __call is always 2 ( http://dictionary.die.net/arity ),  __call( string $methodName, array $arguments), but you can call a method that does not exist using zero or more arguments without limitations. Packing them neatly into an array is the only option, since __call is meant to handle any situation where a method that does not exist is called, regardless of how many arguments are given.

 

If you are using the undefined method setFirstName as a proxy for a set method that does exist or pass it onto another object within scope, you can call call_user_func_array to invoke that method using the arguments array as-is.

 

call_user_func_array(array($class, $method), $argArray)

 

Otherwise, you'll just have to deal with your arguments as an array.

 

$foo->methodDoesNotExist( "foo", "bar", "baz" );
//  __call picks it up  (  __call( $method, $args )  )

(in __call)

var_dump( $method, $args );
/* ==
string "methodDoesNotExist"  // $method
array(3)(   // $args
[0] => "foo",
[1] => "bar",
[2] => "baz"
);
*/

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.