Public/private Properties

Hi!

I have a small problem here and I’m not sure how to handle it.

I have an Active Record model class callsed User. The db table has an attribute "active". Therefore, you can access a property in User class like $User->active.

What I’d like to do now is to disable or disallow direct property access. In normal circumstances I’d define $active property as private but since Yii doesn’t work that way - I can’t. If I define it as private, it doesn’t get set when I load object properties via i.e. findByPK().

The bottom line is - how can I enforce accessing this kind of property only through getters and setters and not directly?

Any suggestions?

Thanx.

Dear Friend

We are accessing and setting attribute values through the magic methods __get() and __set().

This is evident, if we go through the codes of CActiveRecord::__get() and CActiveRecord::__set().

1.getter

2.setter

Regards.

Thanx for your reply. I’m aware of that. This doesn’t answer my question though. Does that mean there’s no way to make a “virtual” property private?

Dear Friend

Actually I have misread that you meant only attributes representing table column names.

So if you declare a virtual attribute as private, we can do the following.

In the example I have declared a private property nativity.




class User extends CActiveRecord

{   

    private $nativity;


//you have to override the getter and setter methods.


    public function __get($name) 

    {

        if(property_exists($this,$name))

	    return $this->$name;

        else return parent::__get($name);

    }

	

    public function __set($name,$value) 

    { 

	if(property_exists($this,$name))

            $this->$name=$value;

	else parent::__set($name,$value);

    }



With this scenario , if you want this virtual property nativity to represent a column in a database,

things are really getting tougher.

It needs lot of customizations and really boring.

I hope I helped a bit.

Regards.

Ok. Thanx. I was hoping there’s a way to handle private properties.