PHP Magic method call

Source: Internet
Author: User
__call is one of the magic methods that calls the __call method when a program calls a method that is not declared in the current class or that does not have permission to call it

Class test{public  function Emptyfunc () {    $getArgs = Func_get_args ();    $funcName = $getArgs [0];    $params = Array_slice ($getArgs, 1);    Var_dump ($params);  This is the 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 "

As in the test class, the Nowtotest method is present, but the method is protected (protection), so the instance of the object does not have permission to execute, then ran to the __call.

_call () has 2 parameters, the first $m is the name of the current calling method, here is ' nowtotest ', and the second $params is the parameter passed in when the ' Nowtotest ' method is called. In the form of an array in $params.

Call_user_func_array ($method, $params) The function of this PHP method is to invoke the $method method, the parameter is $params, if the method is in the class, it is called on the array form above, The Emptyfunc method is called here. The function of Func_get_args () is to get all the parameters passed in as an array. When these parameters are passed in __call, the first parameter is the method name. So the result of the final return is

"Nowtotest function is not exists"
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    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.