Welcome Guest, Not a member yet? Register   Sign In
Setting variables in inherited model
#1

[eluser]Unknown[/eluser]
I'm extending the core Model class to have a generic model I can use that includes basic get/set and database functions.

As part of the new MY_Model I have created an array to hold field names and a __call to deal with get and set functionality. I would like to be able to set these field names up in new models that inherit the MY_Model but I suspect my scope (or at least ordering) is wrong. This doesn't work:
Code:
class MY_Model extends Model
{
    private $id = '';
    private $fields = array();
        
    function MY_Model()
    {
        parent::Model();
    }
}

class Some_model extends MY_Model
{  
    function Some_model()
    {    
                parent::MY_Model();
         $this->fields['name'] = '';
        $this->fields['description'] = '';
    }
}

A print_r on $this->fields shows an empty array.

A solution that works is as follow, but it seems a little kludgey
Code:
class MY_Model extends Model
{
    private $id        =    '';
    private $fields =     array();
        
    function MY_Model($fields)
    {
        parent::Model();
        
        foreach ($fields as $key => $value)
            $this->fields[$key] = $value;
    }
}

class Some_model extends MY_Model
{  
    function Some_model()
    {    
        $fields = array();
         $fields['name'] = '';
        $fields['description'] = '';

        parent::MY_Model($fields);
    }
}

Is there a more elegant way of creating the required array keys?




Theme © iAndrew 2016 - Forum software by © MyBB