php魔術方法call

來源:互聯網
上載者:User
__call是魔術方法中的一個,當程式調用到當前類中未聲明或沒許可權調用的方法時,就會調用__call方法

class test{  public function emptyFunc(){    $getArgs = func_get_args();    $funcName = $getArgs[0];    //$params = array_slice($getArgs, 1);    //var_dump($params);  // this is params                    return $funcName . ' function is not exists';  }  public function __call($m, $params)  {     $arr[] = $m;     $arr = array_merge($arr, $params);     return call_user_func_array(array($this, 'emptyFunc'), $arr);  }  protected function nowToTest(){    return 'this is nowToTest';  }}$testObj = new test();var_dump($testObj->nowToTest('params1','params1'));//var_dump result => string(29) "nowToTest function is not exists"

如上test類中,nowToTest方法是存在的,但修飾這方法的是protected(保護),所以執行個體出來的對象沒許可權執行,這時就跑到__call中去了.

_call()有2個參數,第一個$m是當前調用方法的名字,這裡是'nowToTest',第二個$params是調用'nowToTest'方法時傳入的參數。以數組的形式組合在$params中。

call_user_func_array($method, $params)這個php方法的作用是調用 $method方法,參數為$params,如果方法是在類中的話,就用上面那種數組形式調用就可以了,這裡調用的是emptyFunc方法。 func_get_args()的作用是以數組形式擷取傳入的所有參數。而這些參數在__call中傳入的,第一個參數就是方法名。所以最後返回的結果是

"nowToTest function is not exists"
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.