Read-only object variables in php using magic methods

January 22, 2009

You can create read-only object variables by using the “private” keyword and the __get() and __set() magic methods like this:

class classWithReadOnlyVar
    private $readOnlyVar;

    public function __get($varName)
        return $this->$varName;

    public function __set($varName,$varValue)

So now classWithReadOnlyVar::readOnlyVar is only settable from inside the class, but you can read it from anywhere. For example, if you add the above constructor to the code above:

    public function __construct()
        $this->readOnlyVar = "foo";

Then the following code:

$test = new classWithReadOnlyVar();
echo $test->readOnlyVar;

$test->readOnlyVar = "bar";
echo $test->readOnlyVar;

has this output:


5 Responses to “Read-only object variables in php using magic methods”

  1. Roy Says:

    I understand that the private/public/protected are the access specifiers in oops. where as in your example the variable is defined as private so its scope is limited to only that class.

    But I am bit confuse about the relation between __get() method and making variable readonly. I mean we can have read only variables without __get n __set methods.

    can u please explain more on this

    • cormacscode Says:

      AFAIK you can’t have read-only object variables without __get() and __set() methods. If you can access a variable you can read it and modify it. Am I wrong? Do you know something I don’t?
      How the code above works is access to the variable is set to private, so it can’t be accessed at all from outside the object, and then I use the __get() method to allow it to be read. The empty __set() method is just there to stop an exception being thrown if you try to modify the variable

  2. Willie Says:

    Thanks, you taught me something new!

  3. shaffy Says:

    i understand the code but i m unable to find the declaration of ($this) variable kindly check it.and please help me.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: