2017-04-11 38 views
-2

我搜索一下PHP方法链和所有的教程可以在网络上使用的“返回$此”的方法链接。PHP方法链接,而无需编写大量的回报这

有一个神奇的方法或库,可以使用帮助链接一个类的方法,而无需编写在每一个方法的终结“这回$”。

+0

不存在;除非你使用魔法调用,这不是一个好主意......你在每种方法结束时返回的问题是什么? –

+0

可能在PHP 7.2中的新功能(https://wiki.php.net/rfc/pipe-operator) – Xorifelse

+0

@MarkBaker这是我写的太多了回报$这对我的图书馆 – nonsensecreativity

回答

2

在语言本身是没有办法实现这一点没有return $this。没有指定返回值的函数和方法将在PHP中返回null,如文档中所述:http://php.net/manual/en/functions.returning-values.php

由于null不是具有可调用方法的对象,因此在调用链中的下一项时会引发错误。

你的IDE可能会出现一些功能,使得重复性的任务更容易完成,就像使用片段或正则表达式查找和替换。但除此之外,语言本身目前要求你设计你的班级以便在链接上流利地使用,或者专门设计它不是。


编辑1

我想你可以想见,使用魔法的方法来实现这样的“自动神奇地”。我会建议反对它,因为它是一个可怜的范例,但这并不意味着你不能使它工作。

我的想法是,你可以我们__call魔术方法来包装你的实际方法(http://php.net/manual/en/language.oop5.overloading.php#object.call)。

<?php 

class Whatever 
{ 
    public function __call($method, $parameters) 
    { 
     //If you're using PHP 5.6+ (http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list) 
     $this->$method(...$parameters); 

     //If using < PHP 5.6 
     call_user_func_array(array($this, $method), $parameters); 

     //Always return self 
     return $this; 
    } 

    //Mark methods you want to force chaining on to protected or private to make them inaccessible outside the class, thus forcing the call to go through the __call method 
    protected function doFunc($first, $second) 
    { 
     $this->first = $first; 
     $this->second = $second; 
    } 
} 

所以我认为这是可能的,但同样我个人认为,一个神奇的解决方案,而有效的,散发出显著代码味道,并有可能使其更好地只是处理输入return $this在那里你打算,通过您的设计,以允许链接。

+0

如果你打算兼容5.6以下的兼容性,我只想在'[]'上使用'array()'。 – Xorifelse

+0

好点 - 方括号对任何小于5.4的东西都会造成致命一击。我会改变这一点,以使评论准确。 – stratedge

+0

我认为片段更好。我想在做单元测试时避免将来出现问题等 – nonsensecreativity