Toni Perić
Toni Perić

Reputation: 512

Dynamically calling classes

class App 
{
    public function __construct()
    {
        echo "app is now running...\n";
        $this->getModel('Something');
    }

    public function getModel($name)
    {
        return new $this->getModelInstance($name);
    }

    protected function getModelInstance($name)
    {
        return 'Model_' . $name;
    }
}

I have autoloader set-up and working. Why can't I load Model_Something this way, but I get the following error in return:

Notice: Undefined property: App::$getModelInstance in C:\Apache24\htdocs\ProjectName\app\App.php on line 13

Fatal error: Class name must be a valid object or a string in C:\Apache24\htdocs\ProjectName\app\App.php on line 13

Upvotes: 0

Views: 39

Answers (1)

user3849602
user3849602

Reputation:

Try this :

public function getModel($name) {
  $modelInstanceName = $this->getModelInstance($name);
  return new $modelInstanceName();
}


---
The right way to instantiate a class is :

new Classname($parameter);

So when you were doing this :

new $this->getModelInstance($name);

The class' name was :

$this->getModelInstance

So it was looking for the getModelInstance attribute (and not function) in your App class, which doesn't exist.

Upvotes: 2

Related Questions