php __call()與call_user_func_array()理解
1. mixed __call ( string name, array arguments )
The magic method __call() allows to capture invocation of non existing methods. That way __call() can be used to implement user defined method handling that depends on the name of the actual method being called. This is for instance useful for proxy implementations. The arguments that were passed in the function will be defined as an array in the $arguments parameter. The value returned from the __call() method will be returned to the caller of the method.
譯文: 這個魔術方法允許使用者調用類中不存在的方法,它用於實現那些 依賴於在被調用時的真正方法名的方法. 典型的例子是用來實現代理. 方法的參數$arguments是一個數組 ,__call()的傳回值返回給方法調用者
白話文: 這個方法主要是用來實現動態方法引動過程, 如果再一個類定義了__call()這個方法, 當使用者調用這個類的一個不存在的方法時,他可以使用調用的那個不存在的方法的方法名和參數做出使用者定義在__call()方法體內的相應操作,此時__call()方法的參數就是被調用的那個不存在的方法的方法名和參數
例子
';echo 'and the arguments are
';var_dump( $args );}}$person = new Person();$person->test( 1 , TRUE );?>
程式輸出
引用
you call method test
and the arguments are
array
0 => int 1
1 => boolean true
2. mixed call_user_func_array ( callback function, array param_arr )
Call a user defined function with the parameters in param_arr.
參數
function
The function to be called.
param_arr
The parameters to be passed to the function, as an indexed array.
傳回值
Returns the function result, or FALSE on error.
此方法可以通過傳入類名,類中得方法名和方法參數達到動態調用方法的效果
例子
';echo 'and the arguments are
';var_dump( $args );}} $person = new Person();call_user_func_array( array( $person , 'talk' ) , array( 'hello' ) );?>
程式輸出
引用
hello
兩個方法共用,實現代理模型
class Person{function talk( $sound ){echo $sound;}function __call( $method , $args ){echo 'you call method ' . $method . '
';echo 'and the arguments are
';var_dump( $args );}}class PersonProxy{private $person;function __construct(){$this->person = new Person();}function __call( $method , $args ){call_user_func_array( array( $this->person , $method ) , $args );}}$person_proxy = new PersonProxy(); $person_proxy->talk( 'thank you' );
程式輸出
引用
thank you
1 樓 chinagdvea 2011-12-07