我有以下两个班级. BMW级延伸级轿车.
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());
}
}
您甚至可以从子类反映到父类:
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.
有两种方法可以使相同的方法表现不同:在子类中重写它或者将其重载/传递给它.因为重写它会意味着很多代码重复(你必须在每个子类中基本相同)我建议你在父Car类上构建print_this()方法,如下所示:
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
}
}