Как внедрить объект в методы цепочки php?

это мой php-код, и он не показывает вывод правильно! что я пропустил? правильный путь, показанный после print_r, в конце. methodB и methodC являются необязательными в цепочке, также methodC может вызвать 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 ))
?>

0

Решение

Вывод для первого примера должен быть:

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

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector