我有以下两个班级。宝马级推出了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());
应该只输出子类中的父类属性?任何人都可以帮我吗?
答案 0 :(得分:3)
您可以使用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());
}
}
实际上我想要的是每当我使用类BMW的对象访问print_this()方法时,它应该仅打印BMW类属性,当我使用parent从BMW类访问print_this()时,它应该只打印父类属性。
有两种方法可以使同一方法的行为不同:在子类中重写它或者将它重载/传递给它。由于覆盖它会意味着很多代码重复(你必须在每个子类中基本相同)我建议你在父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
}
}
答案 1 :(得分:0)
尝试
public function print_this()
{
$reflection = new ReflectionClass(__CLASS__);
$properties = $reflection->getProperties();
$propertyValues = [];
foreach ($properties as $property)
{
$propertyValues[$property->name] = $this->{$property->name};
}
print_r($propertyValues);
}
答案 2 :(得分:-1)
您可以尝试这样的事情:
class Car{
public $doors;
public $wheels;
public $color;
public $size;
public function print_this(){
print_r(new Car());
}
}
或者这个:
class Car{
public $doors;
public $wheels;
public $color;
public $size;
public $instance;
public function __constructor(){
$this->instance = new Car;
}
public function print_this(){
print_r($this->instance);
}
}