2014-10-01 126 views
0

我在想,如果我能在PHP中像JavaScript一样,应用函数调用来返回一个对象。在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 

我能做到这一点吗?几乎与C#扩展方法相同。

回答

3

其所谓的方法是包含数字1的阵列链接:

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()); 
0

您可以用功能的恢复工作,但它不是好看的,如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); 

$x应该再经过9