Starmaster
Starmaster

Reputation: 862

PHP OOP about reference

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?

Upvotes: 2

Views: 270

Answers (4)

Stoosh
Stoosh

Reputation: 2429

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

Upvotes: 1

Justin Ethier
Justin Ethier

Reputation: 134177

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.

Upvotes: 1

Joe Mastey
Joe Mastey

Reputation: 27119

$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.

Upvotes: 1

Crozin
Crozin

Reputation: 44376

$a = 'someMethod';
$b = 'someProperty';
$obj->$a()->$b;

is equal to:

$obj->someMethod()->someProperty;

Read more about variable variables

Upvotes: 2

Related Questions