Please refer this
Code input
This code doesn't give the expected output
class User{
protected $name;
protected $age;
public function __construct($name, $age){
$this->name = $name;
$this->age = $age;
}
}
class Customer extends User{
private $balance;
public function __construct($name, $age, $balance){
$this->balance = $balance;
}
public function pay($amount){
return $this->name . ' paid $' . $amount;
}
}
$customer1 = new Customer('Adithya', 23, 50);
echo $customer1->pay(100);
It only gives this
Can someone please explain the reason?
My Answer:
The issue in the code is that the constructor in the `Customer` class is not calling the parent constructor from the `User` class. When you create an instance of the `Customer` class, it should also initialize the properties `$name` and `$age` from the parent class `User`.
To fix this issue, you need to call the parent constructor in the `Customer` class constructor using the `parent::__construct($name, $age);` statement. Here is the updated code:
php
class User{
protected $name;
protected $age;
public function __construct($name, $age){
$this->name = $name;
$this->age = $age;
}
}
class Customer extends User{
private $balance;
public function __construct($name, $age, $balance){
parent::__construct($name, $age);
$this->balance = $balance;
}
public function pay($amount){
return $this->name . ' paid $' . $amount;
}
}
$customer1 = new Customer('Adithya', 23, 50);
echo $customer1->pay(100);
Now, when you create an instance of the `Customer` class, it will properly initialize the properties from both the `User` and `Customer` classes, and you should get the expected output.
Rate this post
4 of 5 based on 4987 votesComments