How to pass a class variable into another class variable as array?

94 views Asked by At

I would like to pass one variable into an array. I have two classes. One MenuClass is used to register menus - and I need the variable populated as an array. I will be using the second class extended, and passing in multiple menus. So I need each run to insert another item into the Main->loaded_menus[] array.

They are loaded in different files, but loaded at the same time. Here is a very basic example of what I am working with...

class Main {

    public $loaded_Menus = array();

    public function __construct() {}

}

class MenuClass {

    public $name;
    public $id;

    public function build($id, $name) {

        $this->id = $id;
        $this-name = $name;

        $populate = new Main;
        $populate->loaded_Menus[$this->id] = $this->id;
    }
}
1

There are 1 answers

0
Javad On BEST ANSWER

When you extend from another class all public properties will be inherited, therefore you don't need to create a new instance of the parent class

class MenuClass extends Main {

   public $name;
   public $id;

   public function build($id, $name) {

     $this->id = $id;
     $this-name = $name;

     $this->loaded_Menus[$this->id] = $this->id;
   }
}

If you want to keep all previous values in your parent class then define it as static; so while your page is alive the values will be kept

class Main {

   public static $loaded_Menus = array();
   public function __construct() {}

}

class MenuClass extends Main {

  public $name;
  public $id;

  public function build($id, $name) {

     $this->id = $id;
     $this-name = $name;

     parent::$loaded_Menus[$this->id] = $this->id;
  }
}