This article mainly introduces PHP object chain operations, and analyzes the simple usage of chain operations and the execution process of object chain operations in the form of instances, which has some reference value, for more information about PHP object chain operations, see the example in this article. We will share this with you for your reference. The details are as follows:
What is a chain operation? Those who use jQuery should be very impressed. in jQuery, we often operate DOM elements like this:
$("p").css("color").addClass("selected");
Coherent operations look really cool and very convenient for reading code. can they be implemented in PHP? The answer is yes. of course, it must be used in OOP. in procedural programs, there is no need to use this method.
In PHP, we often use many functions:
$str = 'abs123 ';echo strlen(trim($str));
The purpose of the above code is to remove spaces on both sides of the string and output its length. then, you can use chained programming as follows:
$str = 'abs123 ';echo $str->trim()->strlen();
Is it more comfortable? Here we mainly use the _ call () and _ toString () magic methods in PHP object-oriented
Class BaseChainObject {/*** trace data for debugging * @ var array */private $ _ trace_data = array (); /*** save the list of available methods * @ param array */protected $ _ methods = array ();/*** processed data * @ param null */public $ data; function _ construct ($ data) {$ this-> data = $ data; $ this-> _ trace_data ['_ construct'] = $ data; return $ this-> data;} function _ toString () {return (String) $ this-> data;} function _ call ($ name, $ args) {try {$ this-> Vaild_func ($ name);} catch (Exception $ e) {echo $ e-> getMessage (); exit () ;}if (! $ Args) {$ args = $ this-> data; $ this-> data = call_user_func ($ name, $ args );} else {$ this-> data = call_user_func_array ($ name, $ args);} $ this-> _ trace_data [$ name] = $ this-> data; return $ this ;} /*** determine whether the method exists * @ param string */private function vaild_func ($ fn) {if (! In_array ($ fn, $ this-> _ methods) {throw new Exception ("unvaild method") ;}} public function trace () {var_dump ($ this-> _ trace_data) ;}} class String extends BaseChainObject {protected $ _ methods = array ('trim', 'strlen ');} $ str = new String ('AB rewqc'); echo $ str-> trim ()-> strlen (); $ str-> trace ();
The code above shows that when calling a method that does not exist in an object, the _ call () magic method is automatically triggered, and then the call_user_func () method is used to perform the chained operation, when the output object is used, toString () is triggered to output the desired result. of course, another solution is to use return this in a custom method, or implement object chain operations. you can try it by yourself.
I hope this article will help you with PHP programming.
For more articles on implementation principles of PHP object chain operations, please refer to PHP Chinese network!