php访问父类的所有属性,php – 在父类中使用$this仅在子类中显示父类属性
发布日期:2021-06-24 11:22:11 浏览次数:3 分类:技术文章

本文共 2038 字,大约阅读时间需要 6 分钟。

我有以下两个班级. 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

}

}

转载地址:https://blog.csdn.net/weixin_32467749/article/details/116258534 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:oracle比较强大的函数,SQL和ORACLE函数比较
下一篇:php tracy,admin.php

发表评论

最新留言

不错!
[***.144.177.141]2024年04月10日 11时37分07秒