Archive for January, 2009

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:

<?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