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

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

报告相同问题?