0
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

1 Answer 1

2

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.

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

7 Comments

I am trying to find the documentation concerning this, I do not want to explain this with wrong words. If someone else can, do not hesitate!
@caCtus not exactly, it's more as if your were calling new [whatever string is returned by getModelInstance()]
@Félix : Why the Undefined property: App::$getModelInstance error and not a Class 'Model_Something' not found error then? (Model_Something is the string returned by getModelInstance() function here) That is how I understood the issue but maybe I am wrong (and maybe PHP tried to do the best it could in this case).
just another explanation, what is happening is that it is trying to create an instance for the property getModelInstance and ($name) is try to call that instances constructor. So if there was a getModelInstance property with the value foo, you are essentially saying new foo($name). Since the property doesn't exist you are saying new {null}($name);. Saving the output to a variable will get you the string as a return which you can call new $string with no problem. I tried stuff like wrapping with parens or braces (which usually works) with no luck.
Also when I tried to solve the problem, I tried new $this->getModelInstance($name)(), but syntax error (same with braces). I have to admit I saw the problem, I saw how to solve it but can't explain clearly why, I don't like it. :) Thanks for your help. @Félix @Jonathan
|

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.