0

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?

Enigma Plus
  • 1,519
  • 22
  • 33
  • Are you sure? That has syntax errors; you mean it without the `;` and with paranthesis? as in _method chaining_ – Damien Pirsy May 21 '14 at 10:05
  • Zend Framework does handle that. But than leave the semicolan after foo and bar – Daan May 21 '14 at 10:05
  • Are you sure about that syntax? I guess you saw a method chaining http://stackoverflow.com/questions/3724112/php-method-chaining – MSadura May 21 '14 at 10:06
  • @Daan - does ZF handle it for directly setting properties like that? Or does it only do so via setters? – Mark Baker May 21 '14 at 10:08
  • @MarkBaker directly you don't need a setter for it. – Daan May 21 '14 at 10:10
  • @Daan - I'm intrigued now, trying to figure out how `$myObj->propertyOne = 'Foo'` could actually return an object instance, unless they're using magic __set() – Mark Baker May 21 '14 at 10:12
  • @MarkBaker Not sure how ZF did manage that. I'm sure you can find it in the documentation http://www.zendframework.com/manual/2.0/en/index.html – Daan May 21 '14 at 10:15

3 Answers3

5

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);
Bartek
  • 1,349
  • 7
  • 13
3

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

Mark Baker
  • 209,507
  • 32
  • 346
  • 385
1

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?

Community
  • 1
  • 1
Enigma Plus
  • 1,519
  • 22
  • 33