如何在php链接方法中注入对象?

如何在php链接方法中注入对象?,php,chaining,Php,Chaining,这是我的php代码,没有以正确的方式显示输出!我错过了什么?打印结束后显示的正确方式。methodB和methodC在链接中是可选的,methodC也可以在methodB之前调用 <?php class FirstClass { public static $firstArray = Array(); public static function methodA($a = null) { self::$firstArray["a"]=$a;

这是我的php代码,没有以正确的方式显示输出!我错过了什么?打印结束后显示的正确方式。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
”方法,所以您总是返回类本身,而不是“content”
$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 ) )

不客气!我希望这是有帮助的,我回答了你所有关于这个的问题!