Let's start with simple PHP code:
<?php
class Test
{
}
$test = new Test();
$test->x = 20;
echo $test->x;
The problem here is this code works without any problem (tested in PHP 7.1, probably in some previous versions it works also without any problems).
The problem I see here that when using code like this, it's very easy to write code that is very hard to analyse and can contain some hidden bugs.
The question: is there any way to don't allow to dynamically create properties for objects especially outside of the class?
For custom class like this the solution that could be used is creating custom __set
method that will creating not declared properties like this:
public function __set($property, $value)
{
if (!property_exists($this, $property)) {
throw new Exception("Property {$property} does not exit");
}
$this->$property = $value;
}
but it obviously doesn't solve problem of protected/private properties - property_exists would return true also for protected and private properties (need to use Reflection for this).