php Creating default object from empty value?

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.


You must use __get magic method - http://php.net/manual/pl/language.oop5.magic.php

You can achieve what you're looking for doing something like that:

<?php
class ModelCreator
{
    private $_modelsCreated = array();
    public function __get($model)
    {
        $class = 'Model'. ucfirst($model);
        //avoid creating multiple same models
        if (!array_key_exists($model, $this->_modelsCreated)) {
            $path = "features". DS ."models". DS . $model .".php";
            require_once 'modeluser.php';
            $this->_modelsCreated[$class] = new $class;
        }
        return $this->_modelsCreated[$class];
    }
}

class MyClass
{
    private $_model;

    public function __construct(ModelCreator $model)
    {
        $this->_model = $model;
    }

    public function __get($name) 
    {
        if ($name === 'model') {
            return $this->_model;
        }
    }
}  

$myClass = new MyClass(new ModelCreator());
$userModel = $myClass->model->user; // will return a class of ModelUser

But you should avoid magic like above -> better approach is to do it that way:

//model creator is an instance of model creator
$this->modelCreator->getModel('user'); // now you know what exactly is happening