Access child property from parent scope

2019-02-12 08:25发布

I need a parent class to access its child properties:

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();

When $_fields is modified from the child scope, it's still null in the parent scope. When trying to access $child_var from parent scope using $this->child_var, it's of course undefined.

I didn't find anything like a "function set" that would just be copied in the child class...

标签: php oop
2条回答
姐就是有狂的资本
2楼-- · 2019-02-12 08:57

Trying to access child values from base(parent) class is a bad design. What if in the future someone will create another class based on your parent class, forget to create that specific property you are trying to access in your parent class?

If you need to do something like that you should create the property in a parent class, and then set it in child:

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(); 

Basically in parent you should not reference child-specific content, because you can't be sure it will be there!

If you have to, you should use abstraction:

PHP Abstraction

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-02-12 09:11

Take a look at an article about visibility.

Basically, you cannot access parent's private properties/methods nor can the parent access its child's. However, you can declare your property/method protected instead.

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();
查看更多
登录 后发表回答