开发者

use $this like return in php classes methods [duplicate]

开发者 https://www.devze.com 2023-03-29 17:56 出处:网络
This question already has answers here: Closed 11 years ago. Possible Dupli开发者_C百科cate: PHP method chaining benefits?
This question already has answers here: Closed 11 years ago.

Possible Dupli开发者_C百科cate:

PHP method chaining benefits?

PHP OOP: Method Chaining

could someone tell me why to use return $this; in a php class method, i have seen that in some method classes like:

public function registerPrefix($prefix, $path)
{

    if(isset($this->prefixes[$prefix])) {
        $path = array_merge($this->prefixes[$prefix], (array) $path);
    }
    $this->prefixes[$prefix] = (array) $path;
    return $this;
}



public function register()
{
    spl_autoload_register(array($this, 'loadClass'));
    return $this;
}

thanks


So that method calls are chainable, e.g.

$myobj->registerPrefix("something", "something")->register();

If you return the object itself from a method call, then you can call methods on the return value of a method.


This allows to call multiple methods of the same objects like this:

$object->registerPrefix(...)->register();

This allows to create fluent/chainable interfaces.


It allows for the chaining of method calls, such as:

$ob->step1()->step2()->step3();

as apposed to:

$ob->step1();
$ob->step2();
$ob->step3();


Generally you use return to make the function return a value.

Specifically you use return $this to return the object.

This sometimes is used for method chaining:

$that = new ThisClass();

$that->does()->what()->ever();

Was modern some-time ago. Can be helpful, but has limits:

$that->does()->what()->ever()->and()->how()->to()->handle()->errors()->and()->very_long()->chains()->question_mark()->exclamation_mark();


This approach allows method chaining, for example:

$object->method1()->method2()->method3();

as opposed to:

$object->method1();
$object->method2();
$object->method3();


$this is usually returned to allow method-chaining...Here's a good link:

http://www.talkphp.com/advanced-php-programming/1163-php5-method-chaining.html


The pseudo-variable $this is available when a method is called from within an object context. $this is a reference to the calling object (usually the object to which the method belongs, but possibly another object, if the method is called statically from the context of a secondary object). You can return whatever you want from a PHP function. It does not have to be $this.

0

精彩评论

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