Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Callable result can't be assigned to array

Tags:

php

I want to add a dog object to an array and var_dump it after but the array stays empty. Am I breaking some rule of the OOP concept or something?

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 );
}
like image 856
Toma Tomov Avatar asked Aug 03 '26 20:08

Toma Tomov


1 Answers

You just need a small change to your MyClass constructor:

Change:

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

to

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

Otherwise you're just setting a value in a local variable, rather than the class property.

like image 82
iainn Avatar answered Aug 06 '26 12:08

iainn