You can create read-only object variables by using the “private” keyword and the __get() and __set() magic methods like this:
<?php
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:
foo foo
April 3, 2009 at 10:01 am
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
April 3, 2009 at 10:12 am
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
May 30, 2010 at 8:19 am
Thanks, you taught me something new!
July 31, 2010 at 7:43 am
i understand the code but i m unable to find the declaration of ($this) variable kindly check it.and please help me.
August 5, 2010 at 1:37 pm
$this refers to the current instance of the class. It’s a standard php thing