开发者

Passing data between classes in PHP

开发者 https://www.devze.com 2023-01-18 22:16 出处:网络
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.

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 in开发者_如何学编程to 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.


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
  }

}
0

精彩评论

暂无评论...
验证码 换一张
取 消