I once questioned a teacher why she used to set properties visibilities as private or protected ALWAYS. She answered me that this is more secure than setting it public, but I'm not really confident in this answer. So, I want to know, even if I ensure that a final user won't have any way to manipulate my classes, is Public property really less secure for properties ? Why ?
No, that's absolute rubbish. It is no more or less secure.
If a user wanted to, they can access a protected/private property on an object:
class Car {
protected $engine = 'V8';
}
$reflector = new ReflectionClass('Car');
$engineProperty = $reflector->getProperty('engine');
$engineProperty->setAccessible(true);
$maserati = new Car;
echo $engineProperty->getValue($maserati); // echoes "V8"
$engineProperty->setValue($maserati, 'I4');
echo $engineProperty->getValue($maserati); // echoes "I4"
So, demonstrably, there is no security benefit.
The benefit is that it helps the end user by marking which functions and properties the class is designed for them to interact with. The developer could totally alter the internals of the class if they wanted to, but the code that calls it wouldn't have to change. If they really want to, the user of the class can muck about with it, but that's their problem if things don't work!
Public properties are not more secure or insecure by themselves as other answers pointed out. But having many public properties can indirectly lead to less secure applications. For example:
Classes with many public properties are more difficult to reason about because those properties can be manipulated by ANY other part of the code instead of just by his own methods. This way the security of the application as a whole can become harder to manage.
In other words: public properties can lead to a bigger attack surface.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With