Sep 08

Read-Only Member Variables with PHP 5

I was talking about Object Oriented Design with someone the other day and the topic of making an object’s member variable read only came up. This is normally a simple task, simply define the member variable as protected or private within the class definition. That essentially makes it inaccessible to any code outside of the class it is a member of. One would then typically define an access function that allows outside code to read the variable. Here is an example:


class readOnly
{
    private $readOnlyVar;

    public function __construct()
    {
        $this->readOnlyVar  = 'This is read only';
    }

    public function getReadOnlyVar()
    {
        return $this->readOnlyVar;
    }
}

$readOnly = new readOnly();
echo $readOnly->getReadOnlyVar();

$readOnly->readOnlyVar = 'Trying to change this';

Running that code would produce the following output:

This is read only
Fatal error: Cannot access private property readOnly::$readOnlyVar

Read the rest of this entry »