【问题标题】:Using more than 1 function in-line from class从类中使用超过 1 个内联函数
【发布时间】:2015-02-27 02:25:11
【问题描述】:

如何从对象内联使用超过 1 个函数? 我有简单的课程:

class test
{
    private $string;

    function text($text)
    {
        $this->string = $text;
    }

    function add($text)
    {
        $this->string .= ' ' . $text;
    }
}

那么我如何使用这个类:

$class = new test();
$class->text('test')->add('test_add_1')->add('test_add_2');

不喜欢:

$class = new test();
$class->text('test')
$class->add('test_add_1')
$class->add('test_add_2')

在 $string 类的末尾将是:test test_add_1 test_add_2

【问题讨论】:

标签: php function class object optimization


【解决方案1】:

您返回$this,以便您可以继续处理该对象:

class test
{
    private $string;

    function text($text)
    {
        $this->string = $text;
        return $this;
    }

    function add($text)
    {
        $this->string .= ' ' . $text;
        return $this;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-22
    • 2020-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多