Reputation: 15375
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...
Upvotes: 23
Views: 25172
Reputation: 11
I think all of answers are not correct !!!!!....notice that you create an object from child class outside of bout classes....so you can access to the parent method (if parent method be public).....and here from inside of parent method you can access to the parent_fields (parent fields should be private because of encapsulation ) and child_fields (child fields should be protected because now you are in parent method)
class Parentclass {
private $parent_fields = "parent field";
public function do_something() {
// Access $_fields and $child_var here
echo $this->parent_fields.PHP_EOL;
echo $this->child_fields;
}
}
class Child extends Parentclass {
protected $child_fields = 'child field';
}
$child = new Child();
$child->do_something();
Upvotes: 0
Reputation: 5622
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:
Upvotes: 12
Reputation: 10356
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();
Upvotes: 22