【问题标题】:PHP - Add function data with dots [duplicate]PHP - 用点添加函数数据[重复]
【发布时间】:2014-03-16 18:12:54
【问题描述】:

我以这个工作示例代码为例...

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');

【问题讨论】:

  • 在 PHP 中 get_childs().add('something1').add('something2').add('something3'); 应该看起来像 get_childs()->add('something1')->add('something2')->add('something3');
  • 你可能注意到了 JQuery 中的方法链 is.gd/EOoIaX

标签: php function


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2014-05-24
    • 2014-09-23
    • 1970-01-01
    • 2013-10-21
    • 2014-04-12
    • 2013-12-08
    • 2016-06-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多