Reading a Non-Existent Property in OOP in PHP
Let's try to write data to a non-existent property - this will work:
<?php
$test = new Test;
$test->prop3 = 3; // write 3
echo $test->prop3; // outputs 3
?>
Suppose we don't want to allow writing to
non-existent properties. And, in general, we want to
allow writing only to properties prop1
and prop2.
This is easy to do - it's enough to add
the corresponding condition in the __set method:
<?php
class Test
{
private $prop1;
private $prop2;
public function __set($property, $value)
{
// Let's write a condition:
if ($property == 'prop1' or $property == 'prop2') {
$this->$property = $value;
}
}
public function __get($property)
{
return $this->$property;
}
}
?>
If there are many such properties, it's not very convenient to list them all in the condition.
Let's put the properties allowed for writing
into an array and check for the presence of the property
in this array using the
in_array function:
<?php
class Test
{
private $prop1;
private $prop2;
public function __set($property, $value)
{
$properties = ['prop1', 'prop2']; // allowed properties
if (in_array($property, $properties)) {
$this->$property = $value;
}
}
public function __get($property)
{
return $this->$property;
}
}
?>