3

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

class test
{
    private $string;

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

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

so how i can use this class as:

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

not like:

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

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

Rizier123
  • 58,877
  • 16
  • 101
  • 156
  • 2
    I believe you have to `return $this` at the end of the function – Djave Dec 30 '14 at 22:45
  • possible duplicate of [PHP method chaining?](http://stackoverflow.com/questions/3724112/php-method-chaining) – OIS Dec 30 '14 at 22:48

1 Answers1

3

You return $this so you can then continue work on the object:

class test
{
    private $string;

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

    function add($text)
    {
        $this->string .= ' ' . $text;
        return $this;
    }
}
Djave
  • 8,595
  • 8
  • 70
  • 124