php - 在类中使用超过 1 个内联函数

标签 php function class object optimization

如何从对象内联使用多个函数? 我有简单的类(class):

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

最佳答案

您返回 $this 这样您就可以继续处理该对象:

class test
{
    private $string;

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

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

关于php - 在类中使用超过 1 个内联函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27713628/

相关文章:

php - "Illegal offset"循环内部

swift - 即使在同一 Controller 中, socket 为零

python - 如何获得在另一个函数中调用的函数以返回值? PYTHON

mysql from_days 产生意外结果

java - Hive UDF 的语义异常错误。我正在尝试通过反转字符串进行测试

php从数组中选择多个随机键

php - 新手问题: table to form generator in php

php - 如何在 SQL 和 PHP 中正确使用 WHERE 和 JOIN

c++ - 将子变量传递给父构造函数

java - 当两个对象相同时,为什么 equals() 方法返回 false?