Bruno Corrêa Zimmermann Bruno Corrêa Zimmermann - 2 months ago 32
PHP Question

PHP - Is public visibility less secure?

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');

$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!