Print_r shows private var. What for?

Why print_rcan I see the private property $ version, even if its area is set as 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);
+4
source share
2 answers

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

print_r(), var_dump() var_export() . . 1

+5

, PHP 5.6.0 __ debugInfo(), , print_r(), var_dump().

, , json encode decode, .

<?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

:

myClass Object
(
    [public_var] => Foobar
)
+1

Source: https://habr.com/ru/post/1667579/


All Articles