Sune
Sune

Reputation: 677

PHP declare class variable from another instance

I have a hard time figuring out how to add a variable value to an instantiated class in php, I've been looking at the reflectionClass and tried to return an assigned variable, and now I'm ended up with a getter setter. I would really appreciate some help, here's an example of my code:

class controller
{

    public $models;

    private $load;

    public function __construct() 
    {
        $this->load = new loader();
    }

    public function action_being_run()
    {
        $this->load->set_model('model_name');
    }

}

class loader
{

    public function set_model($name)
    {
        {controller_class}->models[$name] = new model();
    }

}

The controller class is instantiated without assigning it to a variable, but just:

new controller();

And then the action is executed from within the controller class.

Upvotes: 1

Views: 208

Answers (2)

StackSlave
StackSlave

Reputation: 10627

Like this:

class tester{
  public function lame(){
    return 'super lame';
  }
}
function after(){
  return 'after function';
}
$tst = new tester; $tst->afterVar = 'anything'; $tst->afterFun = 'after';
echo $wh->afterVar;
echo $wh->afterFun();

Upvotes: 0

ollieread
ollieread

Reputation: 6291

You could pass a reference to $this into set_model()

class controller
{

    public $models;

    private $load;

    public function __construct() 
    {
        $this->load = new loader();
    }

    public function action_being_run()
    {
        $this->load->set_model('model_name', $this);
    }

}

class loader
{

    public function set_model($name, &$this)
    {
        {controller_class}->models[$name] = new model();
    }

}

You also need to change public $model to public $models. There are probably other ways to achieve what you want, by either extending a class or just using magic methods to access the model.

Upvotes: 1

Related Questions