我有以下两个类。 BMW 类扩展了 Car 类。
class Car{
public $doors;
public $wheels;
public $color;
public $size;
public function print_this(){
print_r($this);
}
}
class BMW extends Car{
public $company;
public $modal;
public function __construct(){
print_r(parent::print_this());
}
}
$bmw = new BMW();
$bmw->print_this();
在上面的代码中,当我使用 parent::print_this()
和内部 print_this()
方法从构造函数访问父类方法时,我有 print_r($this )
打印所有属性(父类和子类属性)
现在我想要的 print_r(parent::print_this());
应该只在子类中输出父类属性吗?谁能帮我解决这个问题?
最佳答案
您可以使用 reflection 实现此目的:
class Car{
public $doors;
public $wheels;
public $color;
public $size;
public function print_this(){
$class = new ReflectionClass(self::class); //::class works since PHP 5.5+
// gives only this classe's properties, even when called from a child:
print_r($class->getProperties());
}
}
你甚至可以从子类反射(reflect)到父类:
class BMW extends Car{
public $company;
public $modal;
public function __construct(){
$class = new ReflectionClass(self::class);
$parent = $class->getParentClass();
print_r($parent->getProperties());
}
}
编辑:
what actually I want that whenever I access print_this() method using object of class BMW it should print BMW class properties only and when I access print_this() from BMW class using parent it should print only parent class properties.
有两种方法可以使相同的方法表现不同:在子类中覆盖它或重载它/向它传递标志。因为覆盖它意味着大量的代码重复(你必须在每个子类中基本相同)我建议你构建 print_this()
父方法Car
像这样上课:
public function print_this($reflectSelf = false) {
// make use of the late static binding goodness
$reflectionClass = $reflectSelf ? self::class : get_called_class();
$class = new ReflectionClass($reflectionClass);
// filter only the calling class properties
$properties = array_filter(
$class->getProperties(),
function($property) use($class) {
return $property->getDeclaringClass()->getName() == $class->getName();
});
print_r($properties);
}
所以现在,如果您明确想要打印子类的父类属性,只需将标志传递给 print_this()
功能:
class BMW extends Car{
public $company;
public $modal;
public function __construct(){
parent::print_this(); // get only this classe's properties
parent::print_this(true); // get only the parent classe's properties
}
}
关于php - 在父类中使用 $this 仅显示子类中的父类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31122838/