had*_*ley 9 php oop class object parent-child
我有一个父类和一个子类,父类有一个设置一个构造函数,var我想var在子类中使用它,我有它的工作,但我对关键字感到困惑parent?
例
class Sub extends Parent {
public function foo() {
echo $this -> myVar;
}
}
class Parent {
var $myVar;
public function __construct() {
$this -> myVar = 'a';
}
}
Run Code Online (Sandbox Code Playgroud)
这工作,我得到的价值myVar,但我应该使用关键字parent,当我这样做时,我得到一个错误,例如,
class Sub extends Parent {
public function foo() {
echo parent -> myVar;
}
}
class Parent {
var $myVar;
public function __construct() {
$this -> myVar = 'a';
}
}
Run Code Online (Sandbox Code Playgroud)
azi*_*ani 12
首先,Parent是一个保留字.其次,var除非您使用旧版本的PHP,否则请勿使用.你可以使用受保护的.您不需要使用parent关键字来访问变量,因为子类应该继承它.你可以通过它访问它$this->myVar
编辑澄清
只需parent::在访问基类的方法或基类的static变量时使用.如果您尝试访问基类的非静态变量,则会出现错误Access to undeclared static property" fatal error:
这是一个让你入门的例子.
<?php
class Animal{
protected $myVar;
public function __construct() {
$this->myVar = 'a';
}
}
class Cat extends Animal {
public function foo() {
echo $this->myVar;
}
}
$cat = new Cat();
$cat->foo();
?>
Run Code Online (Sandbox Code Playgroud)