tags:

views:

67

answers:

4

Can one please explain with example what does $obj->$a()->$b mean? I've used PHP OOP quite a long time and have seen in some places this structure and not just this $obj->$a(); In what cases should I use it?

Thanks in advance!

+1  A: 
$a = 'someMethod';
$b = 'someProperty';
$obj->$a()->$b;

is equal to:

$obj->someMethod()->someProperty;

Read more about variable variables

Crozin
+1  A: 

$a is the name to a method. Hence, if $a = "myFunc", this is equivalent to:

$obj->myFunc()->$b;

$b appears to be a reference to a property. The method appears to return an object, so, if $b = "myProp", we can modify this to be:

$obj->myFunc()->myprop;

This is really poor form for understandability.

Joseph Mastey
Just to add to this answer, method chaining is fine, if your class interfaces are thoughtful (see jQuery). This isn't method chaining though, it's meta programming.The use of variables here, for object and method names makes debugging harder as you've moved these calls to runtime.I can't say if this decision was a good one because the code isn't given in context.
Greg K
I agree that method chaining is fine. I do think, though, that the fact that we cannot tell whether this code is even reasonable is a pretty good indicator that it isn't. It's trying to be too clever.
Joseph Mastey
+1  A: 

It means that $a() returns an object, and that $b is a member of the object $a() returns.

This is called method chaining when each method returns the original object, so various methods of the same object can be called without having to repeatedly specify $obj-> before each invocation.

Justin Ethier
That could definitely be the case, but may not be chaining if $a returns an object other than $obj.
Joseph Mastey
Right, it is not chaining if different objects are returned. But normally when you see this syntax it is part of a chain. Otherwise I would consider it slightly bad practice.
Justin Ethier
Thanks a lot! Learned a new useful feature in PHP5 OOP for me.
Starmaster
+1  A: 

The actual term is Fluent Interface, as stated is returns the original object, heres a full example class

Class Fluent {
public $var1; 
public $var2;

function setVar1($value) {
    $this->var1 = $value;
    return $this;
}

function setVar2($value) {
    $this->var2 = $value;
    return $this;
}

function getVars() {
    echo $this->var1 . $this->var2;
}
}

$fluent = new Fluent();
$fluent->setVar1("Foo")->setVar2("Bar")->getVars();

Which will obviously return "FooBar".

HTH

Stoosh