dongzexi5125 2012-12-03 20:31
浏览 28
已采纳

PHP在超类中获取属性方法

I want my classes to inherit a getProperties method from its superclass.

class Mother {
  function getProperties(){
    return get_class_vars(get_class($this));
  } 
}

class Child extends Mother{
  private $one = 1;
  private $two = 2;
}

Problem is that if I call getProperties on Child, I get an empty result:

 $c = new Child();
 var_dump( $c->getProperties() );

returns array(0) {}

If I overwrite the getProperties method in Child with the same command, it works as expected and returns array(2) { ["one"]=> int(1) ["two"]=> int(2) }. So I figure that $this is resolved to the Mother class and not to the class that inherited the method. How can I get Child to inherit the method in a way that it works like I need it to? Or how I change the scope of $this to work with Child instead of Mother? Maybe I'm just missing pretty simple fact here so any help is appreciated.

  • 写回答

1条回答 默认 最新

  • doucongmishang2385 2012-12-03 20:36
    关注

    The problem is that your properties are private. That makes them accessible only and exclusively to the declaring class, none other. Make them protected.

    Note though that even then there seem to be some inconsistencies among different PHP versions: http://3v4l.org/1Rm6e

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 seata使用出现报错,其他服务找不到seata
  • ¥15 怎么实现输入一个要删除的数后删除后显示剩余数再输入再删除显示剩余数(语言-c语言)
  • ¥35 引用csv数据文件(4列1800行),通过高斯-赛德尔法拟合曲线,在选取(每五十点取1点)数据,求该数据点的曲率中心。
  • ¥20 程序只发送0X01,串口助手显示不正确,配置看了没有问题115200-8-1-no,如何解决?
  • ¥15 Google speech command 数据集获取
  • ¥15 vue3+element-plus页面崩溃
  • ¥15 像这种代码要怎么跑起来?
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection