I have the following code. I have a Human
class. The Human has properties, like Eyes
, Height
, etc.
Each property is not just a string, but an object, with a protected
value. I assumed I wouldn't be able to access it unless a method belonging to that class returns or prints it. But it gets printed.
I understand that this issue could be exposed without this convolution, but I want to make sure how to handle this case in particular, too - in case I miss something.
class FilterObject {
const FACIAL_FEATURES = ['eyes'];
}
class Property {
protected $value;
public function __construct($value) {
$this->value = $value;
}
public function getValue() {
return $this->value;
}
}
class Eyes extends Property {
const TYPE = 'eyes';
}
class Height extends Property {
const TYPE = 'height';
}
class Human {
protected $height;
protected $wings;
protected $eyes;
public function __construct() {
$this->height = new Height('2 metres');
$this->eyes = new Eyes('blue');
}
public function describeFace() {
$properties = get_object_vars($this);
$properties = array_filter($properties);
$properties = array_filter($properties, function($property){
return in_array($property::TYPE, FilterObject::FACIAL_FEATURES);
});
print_r($properties);
}
}
$john = new Human();
$john->describeFace();
This outputs:
Array ( [eyes] => Eyes Object ( [value:protected] => blue ) )
Why can I see the value Blue? Should I make sure it's not accessible? How do I do that?
Is this somehow because of print_r
?
From the PHP Docs....
print_r(), var_dump() and var_export() will also show protected and private properties of objects. Static class members will not be shown.
print_r is basically a debugging function, so don't use it in your code