Search code examples
phpchaining

How to inject an object in php chaining methods?


this is my php code and didn't show the output in correct way! what did I missed ? the correct way shown after print_r , at the end. methodB and methodC are optional in chaining,also methodC could call befor 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 )) 
?>

Solution

  • 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

    To get the output you expect you could change the method FirstClass::setSeconClass() to

    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 = 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 ) )