The PHP _ call () method is found online.
Lead: http://bbs.17php.com/show_title.php? Id = 1443
A special _ call () method is added to the PHP5 object. this method is used to monitor other methods in an object. If you try to call a method that does not exist in an object, the __call method will be automatically called.
Example 7: __call
Class foo {
Function _ call ($ name, $ arguments ){
Print ("Did you call me? I'm $ name! ");
}
} $ X = new foo ();
$ X-> doStuff ();
$ X-> fancy_stuff ();
?>
This special method can be used to implement the "overload" action, so that you can check your parameters and pass parameters by calling a private method.
Example 8: use _ call to implement "overload" action
Class Magic {
Function _ call ($ name, $ arguments ){
If ($ name = 'Foo '){
If (is_int ($ arguments [0]) $ this-> foo_for_int ($ arguments [0]);
If (is_string ($ arguments [0]) $ this-> foo_for_string ($ arguments [0]);
}
} Private function foo_for_int ($ x ){
Print ("oh an int! ");
} Private function foo_for_string ($ x ){
Print ("oh a string! ");
}
} $ X = new Magic ();
$ X-> foo (3 );
$ X-> foo ("3 ");
?>
Reference:
The _ call and ___ callStatic functions are default functions of the php class,
_ Call () is in the context of an object. If the called method cannot be accessed, it will be triggered.
_ CallStatic () is in a static context. If the called method cannot be accessed, it will be triggered.
Instance:
Abstract class Obj
{
Protected $ property = array ();
Abstract protected function show ();
Public function _ call ($ name, $ value)
{
If (preg_match ("/^ set ([a-z] [a-z0-9] +) $/I", $ name, $ array ))
{
$ This-> property [$ array [1] = $ value [0];
Return;
}
Elseif (preg_match ("/^ get ([a-z] [a-z0-9] +) $/I", $ name, $ array ))
{
Return $ this-> property [$ array [1];
}
Else
{
Exit ("
; Bad function name' $ name '");
}
}
}
Class User extends Obj
{
Public function show ()
{
Print ("Username:". $ this-> property ['username']."
;");
// Print ("Username:". $ this-> getUsername ()."
;");
Print ("Sex:". $ this-> property ['Sex ']."
;");
Print ("Age:". $ this-> property ['age']."
;");
}
}
Class Car extends Obj
{
Public function show ()
{
Print ("Model:". $ this-> property ['model']."
;");
Print ("Sum:". $ this-> property ['Number'] * $ this-> property ['price']."
;");
}
}
$ User = new User;
$ User-> setUsername ("Anny ");
$ User-> setSex ("girl ");
$ User-> setAge (20 );
$ User-> show ();
Print ("
;
;");
$ Car = new Car;
$ Car-> setModel ("BW600 ");
$ Car-> setNumber (5 );
$ Car-> setPrice (40000 );
$ Car-> show ();
?>