php访问父类的所有属性,php – 在父类中使用$this仅在子类中显示父类属性

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

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值