Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 974
bzim Avatar asked Jul 05 '26 03:07

bzim


2 Answers

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!

like image 158
lonesomeday Avatar answered Jul 09 '26 11:07

lonesomeday


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.

like image 24
Wouter de Winter Avatar answered Jul 09 '26 12:07

Wouter de Winter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!