开发者

PHP OOP about reference

开发者 https://www.devze.com 2022-12-23 12:25 出处:网络
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

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?


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

is equal to:

$obj->someMethod()->someProperty;

Read more about variable variables


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


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号