我想知道,在PHP中,是否可以像JavaScript一样,将函数调用应用于对象的返回。在JavaScript中,我可以做到这一点:
var y = 1;
var x = y.toString().concat(' + 1');
console.log(x);
我认为如果有可能在PHP中做几乎相同的事情。我一直在考虑递归,但我不知道搜索它的确切名称。我正在尝试,目前:
<?php
class Main {
public function __construct() {
$this->Main = new Main;
}
public function merge(/* this */ $xs, $ys) {
return array_merge($xs, $ys);
}
public function add(/* this */ $xs, $ys) {
return array_push($xs, $ys);
}
}
$aux = new Main;
$x = $aux -> merge([1, 2, 3], [4, 5, 6])
-> add(7)
-> add(8)
-> add(9);
// $x => [1, 2, 3, 4, 5, 6, 7, 8, 9]
?>
这让一切都溢出来了。我收到溢出消息:
Maximum function nesting level of '100' reached
我能像JavaScript一样做到这一点吗?几乎与C#扩展方法相同。
它被称为方法链接:
class Main {
private $ar = array();
public function merge($xs, $ys) {
$this->ar = array_merge($xs, $ys);
return $this;
}
public function add($ys) {
$this->ar[]= $ys;
return $this;
}
public function toArray(){
return $this->ar;
}
//if you want to echo a string representation
public function __toString(){
return implode(',', $this-ar);
}
}
$aux = new Main;
$x = $aux->merge([1, 2, 3], [4, 5, 6])->add(7)->add(8)-> add(9);
echo $x;
var_dump($x->toArray());
您可以处理函数的返回,但它不如JavaScript:好看
<?php
$array1 = array(1, 2, 3);
$array2 = array(4, 5, 6);
$x = array_push(array_push(array_push(array_merge($array1, $array2), 7), 8), 9);
CCD_ 1应该是一个包含数字1到9的数组。