Reputation: 1548
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
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:
Upvotes: 1
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
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