Private and protected properties of classes are not about security, but provide information about the code for users, to let them know how to use them.

Private and protected properties can be read by converting objects to arrays, closures, or by reverse-engineering using the reflection API.

class Foo
    private $private = "private";
    protected $protected = "protected";

Retrieving the private property value directly results in a fatal error:

$foo = new Foo();
// PHP Fatal error:  Uncaught Error: Cannot access private property Foo::$private in 7.php: 17

Converting to an array:

$foo = (array) $foo;
// string(7) "private"
// string(7) "protected"

Using the reflection API:

$foo = new Foo();
$reflection = new ReflectionObject($foo);
$private = $reflection->getProperty('private');
// string(7) "private"

$protected = $reflection->getProperty('protected');
// string(7) "protected"

Using a closure:

$foo = new Foo();
var_dump((function(){return $this->private;})->bindTo($foo, $foo)());
var_dump((function(){return $this->protected;})->bindTo($foo, $foo)());
// string(7) "private"
// string(7) "protected"

Found a typo? Something wrong with this content?

Just fork and edit it.

Content of this work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license. Code snippets in examples are published under the CC0 1.0 Universal (CC0 1.0). Thanks to all contributors.