开发者

php class extender and parent's construnctor

开发者 https://www.devze.com 2023-02-21 14:11 出处:网络
I have a class class parent { function __construct(){ global $var; } } and another class class child extends parent {

I have a class

class parent {
function __construct(){
global $var;
}
}

and another class

class child extends parent {
function construct(){
parent :: __const开发者_如何学Cruct;
}
function print(){
echo $var;
}
}
$a = new child;
$a->print();

Is there any way to make $var available to the print() method without calling global $var; inside print()?

Thanks!


No, this isn't possible as it's just a global variable and hence doesn't have any special status within the parent or inherited class.

However, you could:

  1. Set an instance (i.e.: class level) variable within the parent class to the same value as the global variable. You'd then use the inherited variable within the child classes print method.

  2. Pass the global variable into the constructor as an argument. You'd would however need to modify both the child (which would pass the variable onto the parent) and parent constructor's.


This is doable if you define $var as a member variable.

class parent {
  public $var;
  function __construct(){
    global $var;
    $this->var = $var;
  }
}

class child extends parent {
  function construct(){
    parent :: __construct;
  }
  function print(){
    echo $this->var;
  }
}

$a = new child;
$a->print();
0

精彩评论

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