在 PHP 中使用方法链接时如何 return 函数值?
How to return function values when using method chaining in PHP?
假设我有以下 class:
class Test
{
private static $instance = false;
public static function test()
{
if(!self::$instance)
{
self::$instance = new self();
}
return self::$instance;
}
public function test1()
{
//...
}
public function test2()
{
//...
}
}
然后我通过像这样链接它们来调用函数:
$data = Test::test(...)->test1(...)->test2(...);
目前,要使上述方法链正常工作,我必须保持 returning $instance
,如果我可以 return 从 test2() 到然后分配给 $data
但我不确定如何执行此操作,因为我必须保持 returning $instance
才能使 mt 方法链工作?
return $this
在 test1()
和 test2()
方法中。
如果你想链接方法,你需要 return 来自任何方法的当前实例,该方法后面有另一个调用链接。但是,链中的最后一个调用没有必要这样做。在这种情况下,这意味着您可以从 test2()
中随意 return
请记住,如果您 return 与 test2()
不同的东西,您以后将永远无法将任何东西链接到它上面。例如,$data = Test::test(...)->test2(...)->test1(...);
将不起作用。
提示:值得用一些注释来记录您的代码,解释哪些是可链接的,哪些不是可链接的,这样您以后就不会忘记。
一般来说,如果您正在进行方法链接,并且我假设上面的每个测试 return 您的数据模型处于不同的状态,并且我假设您需要来自模型本身的一些数据。我会做以下事情:
class Test
{
private static $model;
public function test1() {
//do something to model
return $this;
}
public function test1() {
//do something to model
return $this;
}
public function finish_process() {
//process results
return $this.model;
}
}
所以基本上我现在可以执行以下操作:
$results = Test::test1()->finish_process();
和
$results = Test::test1()->test2()->finish_process();
您可以通过引用传递 $data,您可以更改它或将任何数据分配给它。
// inside class
public function test2( &$data ) {
$data = 'it will work';
}
// outside class
$data = '';
Test::test(...)->test1(...)->test2($data);
假设我有以下 class:
class Test
{
private static $instance = false;
public static function test()
{
if(!self::$instance)
{
self::$instance = new self();
}
return self::$instance;
}
public function test1()
{
//...
}
public function test2()
{
//...
}
}
然后我通过像这样链接它们来调用函数:
$data = Test::test(...)->test1(...)->test2(...);
目前,要使上述方法链正常工作,我必须保持 returning $instance
,如果我可以 return 从 test2() 到然后分配给 $data
但我不确定如何执行此操作,因为我必须保持 returning $instance
才能使 mt 方法链工作?
return $this
在 test1()
和 test2()
方法中。
如果你想链接方法,你需要 return 来自任何方法的当前实例,该方法后面有另一个调用链接。但是,链中的最后一个调用没有必要这样做。在这种情况下,这意味着您可以从 test2()
请记住,如果您 return 与 test2()
不同的东西,您以后将永远无法将任何东西链接到它上面。例如,$data = Test::test(...)->test2(...)->test1(...);
将不起作用。
提示:值得用一些注释来记录您的代码,解释哪些是可链接的,哪些不是可链接的,这样您以后就不会忘记。
一般来说,如果您正在进行方法链接,并且我假设上面的每个测试 return 您的数据模型处于不同的状态,并且我假设您需要来自模型本身的一些数据。我会做以下事情:
class Test
{
private static $model;
public function test1() {
//do something to model
return $this;
}
public function test1() {
//do something to model
return $this;
}
public function finish_process() {
//process results
return $this.model;
}
}
所以基本上我现在可以执行以下操作:
$results = Test::test1()->finish_process();
和
$results = Test::test1()->test2()->finish_process();
您可以通过引用传递 $data,您可以更改它或将任何数据分配给它。
// inside class
public function test2( &$data ) {
$data = 'it will work';
}
// outside class
$data = '';
Test::test(...)->test1(...)->test2($data);