[英]How to inject an object in php chaining methods?
這是我的php代碼,沒有以正確的方式顯示輸出! 我錯過了什么? 最后,在print_r之后顯示正確的方法。 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 ))
?>
第一個示例的輸出應為:
Array ( [a] => qqq [b] => www [c] => eee [secondClass] => SecondClass Object ( ) )
...這就是輸出。 因為是SecondClass
'方法,你總是返回類是自我 ,從來沒有‘內容’ $secondArray
要獲得輸出,您可以將方法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 ) )
或不同地定義$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.