PHP - 为什么我可以在这里打印私人 属性?
PHP - Why can I print a private property here?
我有以下代码。我有一个 Human
class。 Human 具有 Eyes
、Height
等属性
每个 属性 不仅仅是一个字符串,而是一个对象,具有 protected
值。我以为除非属于 class returns 的方法或打印它,否则我将无法访问它。但是它被打印出来了。
我知道这个问题可能会在没有这个卷积的情况下暴露出来,但我也想确定如何特别处理这种情况 - 以防我遗漏了什么。
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();
这输出:
Array ( [eyes] => Eyes Object ( [value:protected] => blue ) )
为什么我可以看到蓝色值?我应该确保它不可访问吗?我怎么做?
这是不是因为 print_r
?
来自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 基本上是一个调试功能,所以不要在你的代码中使用它
我有以下代码。我有一个 Human
class。 Human 具有 Eyes
、Height
等属性
每个 属性 不仅仅是一个字符串,而是一个对象,具有 protected
值。我以为除非属于 class returns 的方法或打印它,否则我将无法访问它。但是它被打印出来了。
我知道这个问题可能会在没有这个卷积的情况下暴露出来,但我也想确定如何特别处理这种情况 - 以防我遗漏了什么。
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();
这输出:
Array ( [eyes] => Eyes Object ( [value:protected] => blue ) )
为什么我可以看到蓝色值?我应该确保它不可访问吗?我怎么做?
这是不是因为 print_r
?
来自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 基本上是一个调试功能,所以不要在你的代码中使用它