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

How to inject an object in php chaining methods?

这是我的 php 代码,没有以正确的方式显示输出!我错过了什么? print_r 之后显示的正确方法,最后。 methodB 和 methodC 在链接中是可选的,也可以在 methodB 之前调用 methodC。

<?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' 方法,你总是 return class 它 self,从来没有 '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 ) )