【问题标题】:How to inject an object in php chaining methods?如何在 php 链接方法中注入对象?
【发布时间】:2018-10-08 20:59:09
【问题描述】:

这是我的 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 )) 
?>

【问题讨论】:

    标签: php chaining


    【解决方案1】:

    第一个例子的输出应该是:

    Array ( [a] => qqq [b] => www [c] => eee [secondClass] => SecondClass Object ( ) )
    

    ...这就是输出。因为是SecondClass' 方法,你总是返回它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 ) )
    

    【讨论】:

    • 不客气!我希望它对您有所帮助,我回答了您所有关于此的问题!
    猜你喜欢
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-24
    • 1970-01-01
    • 1970-01-01
    • 2021-03-02
    • 1970-01-01
    相关资源
    最近更新 更多