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...
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.
In angular there is a scope variable called $parent (i.e. $scope. $parent). $parent is used to access parent scope from child controller in Angular JS.
The reference holding the child class object reference will not be able to access the members (functions or variables) of the child class. This is because the parent reference variable can only access fields that are in the parent class.
Angular scopes include a variable called $parent (i.e. $scope. $parent ) that refer to the parent scope of a controller. If a controller is at the root of the application, the parent would be the root scope ( $rootScope ). Child controllers can therefore modify the parent scope since they access to it.
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();
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With