Welcome Guest, Not a member yet? Register   Sign In
[SOLVED] Is this the correct way of using __set() in a model?
#1

[eluser]Maarten B[/eluser]
Hi all,

I'd like to use PHP5's __set() magic function in a model.

The code below doesn't work; the $this->db is unknown, probably because the model doesn't get properly intialised:
Code:
class PersonAccess extends Model
{
    private $pers_id = null;
    
    function PersonAccess()
    {
        parent::Model();
    }
    
    
    public function __set($name, $value)
    {
        switch($name)
        {
            case 'pers_id':
                if (isset($value) AND is_numeric($value) AND $value >= 1)
                {
                    $this->pers_id = $value;
                }
                else
                {
                    $this->pers_id = null;
                }
                break;
        }
    }
}

When I add a default block to the switch statement, basically saying: "if this class doesn't have the property, try the parent class", it works.
Code:
class PersonAccess extends Model
{

//[snap, same as above]    
    
    public function __set($name, $value)
    {
        switch($name)
        {
            case 'pers_id':

//[snap, same as above]

                break;
            default:  //NEW CODE
                //needed for CI:
                parent::Model()->$name = $value;
        }
    }
}


My question is: is this
Code:
parent::Model()->$name = $value;
the correct way to call the parent ("Model") inside the __set() function?

I mean, I don't get errors, everything seems to work, I just want to be sure.
Other attempts like
Code:
Model()->$name = $value; //doesn't work
parent::$name = $value; //doesn't work
don't work.

Much thanks in advance!


Maarten
#2

[eluser]alpar[/eluser]
why
Code:
parent::Model()->$name = $value;

why wouldn't $this->$name do ? There is no point to assign a the value of a property to a parent since properties are inherited.
#3

[eluser]Maarten B[/eluser]
[quote author="alpar" date="1199029548"]
why wouldn't $this->$name do ? There is no point to assign the value of a property to a parent since properties are inherited.[/quote]

Alpar,
Code:
$this->$name = $value;
in the default part of the switch statement works like a charm!

I made it way too difficult and forgot about the inheritance.

Thanks a lot for replying and reminding me! ;-)

Maarten




Theme © iAndrew 2016 - Forum software by © MyBB