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);
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
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
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With