Welcome Guest, Not a member yet? Register   Sign In
CI 2.0 CI_model And My Own Application Model __get() Conflict?
#1

[eluser]Unknown[/eluser]
I have upgraded from 1.7.3 to 2.0, and I have updated my models and controllers. However, my own application models already use the magic __get() method to access protected properties. Now that 2.0 also uses __get() in the model, I think I have a conflict.

Here's my existing code:
Code:
class Entity_model extends CI_model
{
    /**
     *    Data model for business entities and sites.
     */

    protected $entity_id;
    protected $entity_name;
    protected $entity_description;
    protected $entity_text;

    function __construct()
    {
        parent::__construct();
    }

    /**
     *    Standard magic method to set a class property.
     */
    public function __set($property, $value)
    {
        $this->$property = $value;
    }

    /**
     *    Standard magic method to get a class property.
     */
    public function __get($property)
    {
        // Commented out this condition to help troubleshooting.
        //if(isset($this->$property))        
        {
            return $this->$property;
        }
    }
    
    public function get_site($id)
    {
        $sql = 'SELECT entity_id, entity_name, entity_description, entity_text FROM sites WHERE site_id = ?';
        $query = $this->db->query($sql, array($site_id));
        // More processing here
    }
    
    // More methods...
}

And there's the error:
Code:
Message: Undefined property: Entity_model::$db

// More stuff

Fatal error: Call to a member function query() on a non-object in \application\models\entity_model.php on line 42

Huh? It took me a moment to realize that the call to $this->db->query() was being interpreted as a request to get the DB property in this class.

Is this a bug, or am I using __get() incorrectly? It was working in 1.7.3. I could write my own getter and setter methods of course. When I comment out the magic __get() method the model works fine.

Suggestions? Thanks, Wolf.
#2

[eluser]wiredesignz[/eluser]
Not incorrectly, but you are using __get() wastefully. If the class variables need to be accessed make them public. Remember calling a method to access a variable is slower than accessing the variable directly.

You can always test for available variables and pass the call to parent::__get() if you are concerned about conflicts with CI_Model.




Theme © iAndrew 2016 - Forum software by © MyBB