2011-09-19 155 views
12

我需要一个父类来访问其子属性:访问子属性从父范围

class Parent { 
    private $_fields = null; 

    public function do_something() { 
    // Access $_fields and $child_var here 
    } 
} 

class Child extends Parent { 
    private $child_var = 'hello'; 
} 

$child = new Child(); 
$child->do_something(); 

$_fields从子范围修改,它仍然是在父范围null。当试图使用$this->child_var从父范围访问$ child_var时,它当然是未定义的。

我没有找到像一个“功能设定”,将只在子类中被复制什么...

+4

你可能想使性能'protected',而不是'private'。 –

回答

9

看看文章约visibility

基本上,您无法访问父级的private属性/方法,父级也无法访问其子级。但是,您也可以声明您的财产/方法protected

class Parent { 
    protected $_fields = null; 

    public function do_something() { 
     // Access $_fields and $child_var here 
    } 
} 

class Child extends Parent { 
    protected $child_var = 'hello'; 
} 

$child = new Child(); 
$child->do_something(); 
+0

谢谢!那正是我所期待的。似乎我没有阅读足够的文档。 –

6

试图从基(父)类访问子值是一个糟糕的设计。如果将来有人会根据你的父类创建另一个类,忘记在你的父类中创建你试图访问的那个特定属性?

如果你需要做这样的事情,你应该建立在一个父类的属性,然后将其设置在孩子:

class Parent 
{ 
    protected $child_var; 

    private $_fields = null;  
    public function do_something() 
    {  
     // Access $_fields and $child_var here 
     //access it as $this->child_var 
    } 
} 
class Child extends Parent 
{ 
    $child_var = 'hello'; 
} 

$child = new Child(); 
$child->do_something(); 

基本上在你不应该引用特定的子内容的父母,因为你不能确定它会在那里!

如果你有,你应该使用抽象:

PHP Abstraction

+0

嗯,我知道这是一个不好的做法,但它确实需要它的一个非常具体的情况。无论如何感谢您的回答。 –

+0

我明白这个问题,但这个解决方案仍然让我感到有风险。我们如何执行子类来定义某个属性?我在抽象父类中有一个具体函数,它需要一定的属性。现在我在父类中使用$ this-> childProperty,它运行但是突出显示的问题相同。 –

+0

您可以创建'$ child_var'摘要。这将强制任何孩子实际执行它。 –