php - 在父类中使用 $this 仅显示子类中的父类属性

标签 php oop inheritance

我有以下两个类。 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/

相关文章:

php mysql_query 插入不工作

javascript - 如何分离数据并将其注册到数据库中

PHP/SQL 下一页 - 遵循指南,需要帮助

java - 不继承可以实现多态吗?

javascript - TypeScript 的继承在浏览器端不起作用

c# - 通过向下继承树在 C# 中输入“更宽松”

php - 立即成功消息 - 即使用户很快关闭浏览器,php 脚本也会执行吗?

php - 如何以编程方式从其中一种方法中查找类的公共(public)属性

ruby - 在此 CashRegister 类中查找产品的频率

hibernate - 如何使用 spring-jpa 创建复合键,其中键的一个属性在 @MappedSuperClass 中,而其他属性在 @Entity 类中?