Enigma Plus
Enigma Plus

Reputation: 1548

What is this PHP syntax?

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?

Upvotes: 0

Views: 114

Answers (3)

Enigma Plus
Enigma Plus

Reputation: 1548

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?

Upvotes: 1

Bartek
Bartek

Reputation: 1359

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);

Upvotes: 5

Mark Baker
Mark Baker

Reputation: 212402

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

Upvotes: 3

Related Questions