[英]How to get the value of a variable in child class from parent class
This is the error I am getting:- 这是我得到的错误:
Fatal error: Cannot use 'Parent' as class name as it is reserved in C:\\xampp\\htdocs\\test\\home.php on line 3
致命错误:无法在第3行的C:\\ xampp \\ htdocs \\ test \\ home.php中保留'Parent'作为类名
Here is my code: 这是我的代码:
<?php
class Parent{
public $num1 = 3;
}
class Child extends Parent{
public $sum = 2 + $this->num1;
}
$obj = new Child();
echo $obj->sum;
?>
You can't use Parent
as a class name and you can assign $sum
an initial value using $sum = 2 + $this->num1;
不能使用
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;
You have defined variable in the wrong way, The variable should be var $num = 3; 您以错误的方式定义了变量,该变量应为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.