Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

print_r shows private var. Why?

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);
like image 526
Benjamin H Avatar asked Dec 10 '22 13:12

Benjamin H


2 Answers

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

like image 118
Sᴀᴍ Onᴇᴌᴀ Avatar answered Jan 02 '23 12:01

Sᴀᴍ Onᴇᴌᴀ


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
)
like image 43
Lawrence Cherone Avatar answered Jan 02 '23 12:01

Lawrence Cherone