4

Why can print_r see the private property $version even when its scope is set to private?

class myClass {

    private $version;

    public function set_version($value){
        $this->version = $value;
    }


}



$class = new myClass();
$class->set_version("1.2");

echo "<pre>";
print_r($class);
Sᴀᴍ Onᴇᴌᴀ
  • 8,218
  • 8
  • 36
  • 58
Benjamin H
  • 65
  • 1
  • 9
  • `private` object properties are primarily in the context of class inheritance, and internal scope, only. – Martin Jan 24 '17 at 16:14
  • Don't assume that `private` means "secure". It's only an indicator for how this property *should be used*, it doesn't provide any actual "security" or in fact "real privacy". – deceze Jan 24 '17 at 16:14
  • @deceze Private means that it's only in side the specific class there can read and update the value of the var or function. that why I was wondering about how the print_r still could see it – Benjamin H Jan 24 '17 at 20:07

2 Answers2

8

print_r() shows private member properties for debugging purposes. It should not be used to output an object for display purposes (e.g. in a view/page). To display information about an object, it would likely be appropriate to create a method (e.g. toString) that will return the appropriate information.

print_r(), var_dump() and var_export() will also show protected and private properties of objects. Static class members will not be shown.1


1http://php.net/manual/en/function.print-r.php#refsect1-function.print-r-description

Sᴀᴍ Onᴇᴌᴀ
  • 8,218
  • 8
  • 36
  • 58
  • Why not static class? – TheCrazyProfessor Jan 24 '17 at 18:08
  • Thanks man! :D well @TheCrazyProfessor thats a good question. – Benjamin H Jan 24 '17 at 20:04
  • @TheCrazyProfessor I presume it is an internal storage thing... e.g. maybe PHP stores the static variables with the class definition in one object and then instances of that class are in a separate object... If you really want those, you could use a [Reflection class](http://php.net/manual/en/reflectionclass.construct.php) (see [this answer](http://stackoverflow.com/questions/8763994/how-can-i-get-a-list-of-static-variables-in-a-class#answer-8764052) for more info also) – Sᴀᴍ Onᴇᴌᴀ Jan 24 '17 at 20:09
5

Additionally, as of PHP 5.6.0 you can use __debugInfo(), which will allow you to override or refine what print_r(), var_dump() outputs.

So for example, using json encode and decode, you can return only the public properties.

<?php
class myClass {

    private $private_var;

    public $public_var = 'Foobar';

    public function setPrivate($value)
    {
        $this->private_var = $value;
    }

    public function __debugInfo()
    {
        return json_decode(json_encode($this), true);
    }
}

$class = new myClass();
$class->setPrivate("Baz");

print_r($class);

https://3v4l.org/seDI6

Result:

myClass Object
(
    [public_var] => Foobar
)
Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106