Three methods for implementing chained operations in PHP are described in detail, and three methods for linking
This article describes three methods for PHP to implement chained operations. We will share this with you for your reference. The details are as follows:
There are many character string functions in php. For example, you need to filter the spaces ending with the character string before finding its length. The general syntax is:
strlen(trim($str))
If you want to implement chained operations similar to those in js, such as how to write them like the following?
$str->trim()->strlen()
The following are implemented in three ways:
Method 1: use the magic function _ call and call_user_func.
Thoughts:First define a string class StringHelper, the constructor directly Assigns value, and then calls trim () and strlen () functions in a chain, through the magic function _ call () called in () call_user_func is used to process the call relationship. The implementation is as follows:
<?phpclass StringHelper { private $value; function __construct($value) { $this->value = $value; } function __call($function, $args){ $this->value = call_user_func($function, $this->value, $args[0]); return $this; } function strlen() { return strlen($this->value); }}$str = new StringHelper(" sd f 0");echo $str->trim('0')->strlen();
Terminal execution script:
php test.php 8
Method 2: Use the magic function _ call and call_user_func_array.
<?phpclass StringHelper { private $value; function __construct($value) { $this->value = $value; } function __call($function, $args){ array_unshift($args, $this->value); $this->value = call_user_func_array($function, $args); return $this; } function strlen() { return strlen($this->value); }}$str = new StringHelper(" sd f 0");echo $str->trim('0')->strlen();
Note:
Array_unshift (array, value1, value2, value3 ...)
array_unshift()The function is used to insert new elements into the array. The value of the new array is inserted at the beginning of the array.
call_user_func()Andcall_user_func_arrayThey all call functions dynamically. The difference is that parameters are transmitted in different ways.
Method 3: Do not use the magic function _ call.
You only need to modify_call()Istrim()Function:
public function trim($t){ $this->value = trim($this->value, $t); return $this;}
The focus is that the $ this pointer is returned to facilitate the latter function call.