2012-12-16 100 views
-1

我在使用子类静态方法访问父级(非静态)属性时遇到问题。我已经试过这些如下:如何在静态方法中访问父非静态属性,在PHP中?

class Parent 
{ 
    protected $nonStatic; 
    // Other methods and properties 
} 

class Child extends Parent 
{ 
    public static function staticFunc() 
    { 
     $test = $this->nonStatic;  # Using $this when not in object context 
     $test = self::$nonStatic;  # Access to undeclared static property 
     $test = parent::$nonStatic # Access to undeclared static property 
    } 
} 

我检查了计算器类似的问题,但我没有得到任何有效的解决方案


附:对不起错别字,和上面的代码是一个虚拟的例子

+0

代码,例如,提供,甚至没有编译。请确保您提供的代码实际上以您期望的相同方式失败。 – Charles

+0

这里有很多错误:不是'protect $ nonStatic;'但是'protected $ nonStatic;','$ this'这个用法在静态上下文中...... –

+0

那么如果你从实际代码中复制并粘贴了上面的代码,问题是这个'protect $ nonStatic;'它应该是'protected $ nonStatic;'仔细检查你粘贴的内容。 – PhearOfRayne

回答

1

显然,静态方法不会知道非静态父属性是什么。它不知道正在调用哪个对象的实例 - 因此它无法知道该对象是否为父对象。无论是家长道具设置为静态或子对象的实例传递给方法,并调用passedChildObject.parentProp

public static function staticFunc(Child c) 
{ 
//should give you passed instance parent prop 
return c.$nonStatic 
} 

现在,当你想要的属性..

{ 
//assume x is already initialized, this is just for clarity 
Child x; 
returnedProp = x.staticFunc(x) 
} 
+0

谢谢,正如我在问题中所说的评论,我正在改变一个项目设计模式,所以我在这里问是否可能,然后通过阅读你的答案我明白我错在哪里 – Behzadsh

1

制作父母的财产太静。 否则在静态上下文中无法访问它。

+0

这可能是一个解决方案: )谢谢 – Behzadsh

4

你不能从一个静态方法访问父非静态属性,因为这是不可能的定义,是没有意义的。

非静态属性可用的,当你有一个对象实例,而你没有任何。

相关问题