Using more than 1 function in a line from a class

How can I use more than 1 inline function from an object? I have a simple class:

class test
{
    private $string;

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

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

      

so how can i use this class like:

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

      

I do not like:

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

      

And at the end, in the $ string class will be: test test_add_1 test_add_2

+3


source to share


1 answer


You return $this

to continue working on the object:



class test
{
    private $string;

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

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

      

+4


source







All Articles