[英]How to inject an object in php chaining methods?
this is my php code and didn't show the output in correct way! 这是我的php代码,没有以正确的方式显示输出! what did I missed ? 我错过了什么? the correct way shown after print_r , at the end. 最后,在print_r之后显示正确的方法。 methodB and methodC are optional in chaining,also methodC could call befor methodB. methodB和methodC在链接中是可选的,methodC也可以在methodB之前调用。
<?php
class FirstClass
{
public static $firstArray = Array();
public static function methodA($a = null)
{
self::$firstArray["a"]=$a;
return new static;
}
public function methodB($b = null)
{
self::$firstArray["b"]=$b;
return new static;
}
public function methodC($c = null)
{
self::$firstArray["c"]=$c;
return new static;
}
public function setSeconClass($sc)
{
self::$firstArray["secondClass"]=$sc;
return self::$firstArray;
}
}
class SecondClass
{
public static $secondArray = Array();
public static function methodA($a = null)
{
self::$secondArray["a"]=$a;
return new static;
}
public function methodB($b = null)
{
self::$secondArray["b"]=$b;
return new static;
}
public function methodC($c = null)
{
self::$secondArray["c"]=$c;
return new static;
}
}
$sc = SecondClass::methodA("xxx")->methodB("yyy")->methodC("zzz");
$fc = FirstClass::methodA("qqq")->methodB("www")->methodC("eee")->setSeconClass($sc);
print_r($fc); // outpute should be ---> Array ( [a] => qqq [b] => www [c] => eee [secondClass] => Array ( [a] => xxx [b] => yyy [c] => zzz ))
$sc = SecondClass::methodA("xxx");
$fc = FirstClass::methodA("qqq")->setSeconClass($sc);
print_r($fc); // outpute should be ---> Array ( [a] => qqq [secondClass] => Array ( [a] => xxx ))
?>
The output for the first example should be : 第一个示例的输出应为:
Array ( [a] => qqq [b] => www [c] => eee [secondClass] => SecondClass Object ( ) )
...and that's what the output is. ...这就是输出。 Because is SecondClass
' methods you always return the class it self , never the 'content' $secondArray
因为是SecondClass
'方法,你总是返回类是自我 ,从来没有‘内容’ $secondArray
To get the output you expect you could change the method FirstClass::setSeconClass()
to 要获得输出,您可以将方法FirstClass::setSeconClass()
更改为
public function setSeconClass($sc)
{
self::$firstArray["secondClass"]=$sc::$secondArray; // set the array here, not the class
return self::$firstArray;
}
// OUTPUT:
Array ( [a] => qqq [b] => www [c] => eee [secondClass] => Array ( [a] => xxx [b] => yyy [c] => zzz ) )
or define $sc
differently: 或不同地定义$sc
:
$sc = SecondClass::methodA("xxx")->methodB("yyy")->methodC("zzz")::$secondArray;
// again, setting the array as $sc, not the (returned/chained) class
// OUTPUT:
Array ( [a] => qqq [b] => www [c] => eee [secondClass] => Array ( [a] => xxx [b] => yyy [c] => zzz ) )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.