在父类中使用$this只显示子类中的父类属性


show only parent class properties in child class using $this in parent class

我有以下两个类。宝马级扩展了轿车级。

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());应该只输出子类中的父类属性?有人能帮我吗?

您可以使用反射来实现这一点:

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_thi()时,它只打印parent类属性。

有两种方法可以使同一个方法表现得不同:在子类中重写它或重载它/向它传递标志。由于重写它意味着大量的代码重复(在每个子类中必须基本相同),我建议您在父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
    }
}

尝试

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);
}

你可以试试这样的东西:

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);
  }
}