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
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;
.
// 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;
class Parent{
var $num1 = 3;
}
class Child extends Parent{
public function sum() {
return 2 + $this->num1;
}
}
$obj = new Child();
echo $obj->sum();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.