Alex Rivera | Logout

read-only properties in PHP?

Asked 2010-08-30T13:28:34.497
15

Is there a way to make a read-only property of an object in PHP? I have an object with a couple arrays in it. I want to access them as I normally would an array

echo $objObject->arrArray[0];

But I don't want to be able to write to those arrays after they're constructed. It feels like a PITA to construct a local variable:

$arrArray = $objObject->getArray1();
echo $arrArray[0];

And anyways, while it keeps the array in the object pristine, it doesn't prevent me from re-writing the local array variable.

Edit
Report

1 Answer

4

If defined, the magic functions __get() and __set() will be called whenever a non-existing or private property is accessed. This can be used to create "get" and "set" methods for private properties, and for instance make them read-only or manipulate the data when stored or retrieved in it.

For instance:

class Foo
{
  private $bar = 0;
  public $baz = 4; // Public properties will not be affected by __get() or __set()
  public function __get($name)
  {
    if($name == 'bar')
      return $this->bar;
    else
      return null;
  }
  public function __set($name, $value)
  {
    // ignore, since Foo::bar is read-only
  }
}

$myobj = new Foo();
echo $foo->bar; // Output is "0"
$foo->bar = 5;
echo $foo->bar; // Output is still "0", since the variable is read-only

See also the manual page for overloading in PHP.

answered 2010-08-30T13:33:23.387

Your Answer