php _call()與call_user_func_array()瞭解

來源:互聯網
上載者:User
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

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.