How to use __call () and __callstatic () in PHP

Source: Internet
Author: User
This article is mainly to share with you PHP __call () and __callstatic () use of methods, hope to help everyone. For the use of these two methods, do not do too much explanation, through the example code and results, you can more clearly understand the role of both.

1.__call () method. When calling a method that is not declared in a class, you can call the __call () method instead of declaring a method. Accept the method name and array as parameters.

code example:

<?php  class test{  //Magic Method __call/  * $method Get the method name $arg get the parameter collection for the method */public  function __call ($method, $ ARG) {      echo ' you want to call the method I don't exist ', $method, ' method <br/> ';      Echo ' also transmitted a parameter <br/> ';      echo Print_r ($arg), ' <br/> ';    }   $list =new Test ();  $list->say (a);    ? >

Execution Result:

You want to call the way I don't exist say method
And a parameter was passed.
Array ([0] = 1 [1] = 2 [2] = 3)

2.__callstatic () method. This method appears from PHP5.3, when you create a static method to call a method that does not exist in the class, use this function. As with the __call () method, the method name and array are accepted as parameters.

code example:

<?php  class test{  //Magic Method __callstatic/* $method Get Method name $arg get the parameter collection of method *  //Magic method __callstatic  Public static function __callstatic ($method, $arg) {        echo ' you want to call me nonexistent ', $method, ' static method <br/> ';      Echo ' also transmitted a parameter <br/> ';      echo Print_r ($arg), ' <br/> ';    }    }  Test::cry (' Cry ', ' ghost cry ', ' howler ');  >

Execution Result:
You want to call the cry static method that I don't exist
And a parameter was passed.
Array ([0] = crying [1] = Ghost cry [2] = = Howler)

Related Article

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.