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
Derek is a software and web developer in Orlando, FL. Check back often for updates on Orlando and Technology.