![](/img/trans.png)
[英]How to get Parent class variable value in child class construct method
[英]How to get the value of a variable in child class from parent class
这是我得到的错误:
致命错误:无法在第3行的C:\\ xampp \\ htdocs \\ test \\ home.php中保留'Parent'作为类名
这是我的代码:
<?php
class Parent{
public $num1 = 3;
}
class Child extends Parent{
public $sum = 2 + $this->num1;
}
$obj = new Child();
echo $obj->sum;
?>
不能使用Parent
作为一个类的名字,你可以为$sum
使用初始值$sum = 2 + $this->num1;
。
// renamed parent class
class ParentClass {
public $num1 = 3;
}
// renamed child class
class ChildClass extends ParentClass {
public $sum ;
// a constructor is where you would do this type of math
function __construct() {
$this->sum = 2 + $this->num1;
}
}
// create your child object
$obj = new ChildClass();
echo $obj->sum;
您以错误的方式定义了变量,该变量应为var $ num = 3;
class Parent{
var $num1 = 3;
}
class Child extends Parent{
public function sum() {
return 2 + $this->num1;
}
}
$obj = new Child();
echo $obj->sum();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.