用圆点添加函数数据


PHP - Add function data with dots

我有这个工作样例代码为例…

function get_childs() {
    $array = array(1 => 'item1', 2 => 'item2', 3 => 'item3');
    return $array;
}
function add( $array, $item ) {
    $array[] = $item;
    return $array;
}
function array_delete( $array, $key ) {
    unset( $array[$key] );
    return $array;
}
$result_array = array_delete( add( get_childs(), 'test' ), 2 );
print_r( $result_array );

改为箭头

现在代码的一部分看起来像这样(相当难看):

array_delete( add( get_childs(), 'test' ), 2 );

我在网上看到可以这样做:

get_childs().add('test').delete(2);

更漂亮。它是如何完成的?

一个旁注

我看到这样调用的函数可以像这样重复:

get_childs().add('something1').add('something2').add('something3');

最简单的方法是将此功能移到类中,例如:

class MyCollection
{
    private $arr;
    public function create_childs()
    {
        $this->arr = array(1 => 'item1', 2 => 'item2', 3 => 'item3');
        return $this;
    }
    public function get_childs()
    {
        return $this->arr;
    }
    public function add($item)
    {
        $this->arr[] = $item;
        return $this;
    }
    public function delete($key)
    {
        unset($this->arr[$key]);
        return $this;
    }
}
$collection = new MyCollection();
print_r($collection->create_childs()->add("test")->delete(2)->get_childs());