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.

我希望我的类从其超类继承getProperties方法。 p>

   class Mother {
 function getProperties(){
 return get_class_vars(get_class($ this)); 
} 
} 
 
class Child extends Mother {
 private $ one = 1; 
 private  $ 2 = 2; 
} 
  code>  pre> 
 
 

问题是,如果我在Child上调用getProperties,我会得到一个空结果: p> $ c = new Child(); var_dump($ c-> getProperties()); code> pre>

返回数组( 0){} code> p>

如果我使用相同的命令覆盖Child中的getProperties方法,它将按预期工作并返回 array(2){[“one” ] => int(1)[“two”] => int(2)} code>。 所以我认为 $ this code>已经解析为Mother类而不是继承该方法的类。 我如何让Child继承方法,使其工作方式就像我需要它一样 ? 或者我如何将 $ this code>的范围更改为使用Child而不是Mother? 我可能在这里错过了非常简单的事实,所以任何帮助都会受到赞赏。 p> div >

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