What is this PHP syntax?

2019-03-06 15:20发布

I recently saw some sample PHP code that looked like this:

$myObj->propertyOne = 'Foo'
      ->propertyTwo = 'Bar'
      ->MethodA('blah');

As opposed to:

$myObj->propertyOne = 'Foo';
$myObj->propertyTwo = 'Bar';
$myObj->MethodA('blah');

Is this from a particular framework or a particular version of PHP because I have never seen it work?

3条回答
混吃等死
2楼-- · 2019-03-06 15:41

I can't believe that it would actually work as you've shown it with the semi-colons after each line, nor for assigning properties directly; you may well have seen something like

$myObj->setPropertyOne('Foo')
      ->setPropertyTwo('Bar')
      ->MethodA('blah');

which is commonly called a fluent interface or method chaining, where each of the methods returns the instance of the current object via return $this

查看更多
狗以群分
3楼-- · 2019-03-06 15:53

I've had a look at Method Chaining which I'd never heard of in PHP before. Obviously my example is nonsense.

This post makes sense of it for me:

PHP method chaining?

查看更多
Emotional °昔
4楼-- · 2019-03-06 15:59

What you saw was fluent interface, however your code sample is wrong. To make long story short, fluent setter should return $this:

class TestClass {
    private $something;
    private $somethingElse;

    public function setSomething($sth) {
        $this->something = $sth;

        return $this;
    }

    public function setSomethingElse($sth) {
        $this->somethingElse = $sth;

        return $this;
    }
}

Usage:

$sth = new TestClass();
$sth->setSomething(1)
    ->setSomethingElse(2);
查看更多
登录 后发表回答