Search code examples
phpmodel-view-controllerstandards

php Creating default object from empty value?


ok what im trying to do is makeing something so i can call it like $this->model->users->getInfomation('name'); or something similer on my framework but php give me a strict standards Creating default object from empty value

protected function model($model)
{
    $path = "features". DS ."models". DS . $model .".php";
    require $path;

    $class = 'Model'. ucfirst($model);
    $this->model->$model = new $class;
}

can we make it so it will somehow fit in the standards ?

edit*

this function is in class Application so i can extend them from our controller like blog Extends Application then call something like $this->model->blog will get something like what im doing above, when i do something like

protected function model($model)
{
    $path = "features". DS ."models". DS . $model .".php";
    require $path;

    $class = 'Model'. ucfirst($model);
    $this->$model = new $class;
}

yes the above code works fine $this->blog->getSomething();, but somehow i want to make them in a group, like the question above, so if we want to get something like $this->model->blog->getSomething();

Thanks for the time.

Adam Ramadhan


Solution

  • It's hard to see what you're actually doing wrong with that code alone. I've made some very simple code to reproduce the error:

    <?php
    $bar = 42;
    $foo = null;
    
    $foo->bar = $bar;
    

    The reason it gives this warning, is that you're assigning values the "object way", but you're assigning it to a variable that isn't an object. By doing this, the Zend engine actually creates an object for $foo, which is an instance of StdClass. Obviously, 9 out of 10 times, this isn't what you want to do, so PHP provides a helpful message.

    In your case: $this->model isn't an object (yet). If you want to get rid of the error, just do:

    if( !is_object( $this->model ) ) {
        $this->model = new StdClass;
    }
    $this->model->$model = new $class;
    

    Cheers.