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...
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:
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
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/methodprotected
instead.