1

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.

1
  • You could inject the controller object in the constructor of the loader object; $this->load = new loader($this);, etc. Commented Dec 18, 2013 at 1:37

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! That must be the only thing i haven't thought of. Thank you! :)
0

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.