tags:

views:

65

answers:

1

A couple of questions: q1:

IN OOP PHP, what is the best way for a child class to make use of a var set by the parent class, and to set a variable in the parent class.

What I want to do is run a function in the child class, that uses one of the variables in the parent class.

I have done it by setting the variable I want to access as public, and entering it into the child class as an argument when calling the function, but it would be better if I could simply get it within the child class's function.

Then, to set the variable in the parent class with the result of that function, I have returned the value into a setter class of the parent function. Here it is all in action:

$parentClass->set_maxpages($childClass->setMaxPages($cparentClass->contents));

Q2:

When I instantiate the child class, it runs the paren'ts constructor. If the child class has a constructor of its own, does it override the parnt class constructor.

+4  A: 

You can access public and protected parent member variables via $this->varname:

class Parent
{
  public $pub = 1;     // anybody can access this
  protected $pro = 2;  // Parent and its children can access this
  private $pri = 3;    // only Parent can access this
}

class Child extends Parent
{
  public function __construct()
  {
     // overrides parent's __construct
     // if you need to call the parent's, you must do it explicitly:
     parent::__construct();

     var_dump($this->pub); // 1
     var_dump($this->pro); // 2
     var_dump($this->pri); // null ... not set yet because it's private
  }

}
konforce
Brilliant, what about setting the var in the parnt class
Liam Bailey
They are the same object, so they are working with the same `public` or `protected` variables in either direction. The `private` variables are hidden in both directions.
konforce
This doesn't work for me. I was able to set the variable in parent class with parent::set_maxpages(); but I can't access the variables in the parent class, I even copied and pasted your code to try. No errors but no output either?
Liam Bailey
Well, this is a curious bit: `$parentClass` and `$childClass`. That suggests that you are working with two different objects. You should have a single object that was created with `$child = new Child();`. Then you can call `$child->parentMethod()` or `$child->childMethod()`. If that doesn't help, then you should edit your answer with a small, but complete, example of what isn't work.
konforce
`parent::set_maxpages()` would be a _static_ function (a static variable is accessible with a `parent::$whatever` if you really set a static variable). Don't mix/match/mistake instances for their static presence.
Wrikken
Correct, I instantiated a parent, then a child class, with the data from $parentclass->dataOut sent into the childs constructor. Too long between learning OOP and putting it into practice. I will go now and do it the right way.
Liam Bailey