我想在数组中添加一个dog对象,然后var_dump它,但是数组保持为空。我是不是违反了面向对象编程的一些规则?

class Dog {

    public $name;
    public $bread;

}

class MyClass {

    public $dogArr = [];

    public function __construct( $key , callable $callback ) {
        $dogArr[$key] = $callback ();
    }

}

public function actionTest() {

    $newDog = new \backend\components\MyClass ( "first" , function () {
        $dog = new \backend\components\Dog();
        $dog->name = "Archi";
        $dog->bread = "Pomeran";
        return $dog;
    } );

    var_dump ( $newDog->dogArr );
}

最佳答案

您只需要对MyClass构造函数做一点小小的更改:
变化:

$dogArr[$key] = $callback();


$this->dogArr[$key] = $callback();

否则,您只是在局部变量中设置值,而不是在类属性中设置值。

10-07 17:45