Reputation: 601
I created Person
class, then extended it to Student
class. When I call a method on a Student
object, it doesn't work as expected.
Here is my code
class Person{
static public $IsAlive;
public $FirstName;
public $LastName;
public $Gender;
public $Age;
static public $total_person = 1;
static public $type;
function __construct($FirstName,$LastName,$Gender,$Age,$IsAlive,$type=""){
self::$IsAlive = $IsAlive;
if(self::$IsAlive === TRUE){
echo "<strong>Person Number#" . self::$total_person++ . "</strong> details are given below: <br />";
$this->FirstName = $FirstName;
$this->LastName = $LastName;
$this->Gender = $Gender;
$this->Age = $Age;
self::$type = $type;
}else{
echo "This Person is not longer available <br />";
}
}
function PersonDetail(){
if(self::$IsAlive === TRUE){
echo "Person Name: " . $this->FirstName . " " . $this->LastName . "<br />";
echo "Person Gender: " . $this->Gender . "<br />";
echo "Age: " . $this->Age;
}
}
}
class Student extends Person{
public $standard = "ABC";
public $subjects = "ABC";
public $fee = "123";
function StudentDetail(){
if(parent::$type === "Student"){
return parent::PersonDetail();
echo "Education Standard: " . $this->standard;
echo "Subjects: " . $this->subjects;
echo "Fee: " . $this->fee;
echo parent::$type;
}
}
}
$Hamza = new Student("Muhammad Hamza","Nisar","Male","22 years old",TRUE,"Student");
$Hamza->StudentDetail();
It's printing PersonDetail()
only, but not printing the complete information like education standard, subjects and fee.
Here is my Output
Person Number#1 details are given below:
Person Name: Muhammad Hamza Nisar
Person Gender: Male
Age: 22 years old
I need to see the StudentDetail()
output below it as well. What's wrong and how to fix it?
Upvotes: 0
Views: 51
Reputation: 14938
If you put a return
statement inside your function (or method), PHP will not proceed the execution after this point (most of the time)*. So, when the following code (taken from your question) is executed, it stops after you call return parent::PersonDetail();
.
function StudentDetail() {
if(parent::$type === "Student") {
return parent::PersonDetail();
echo "Education Standard: " . $this->standard;
echo "Subjects: " . $this->subjects;
echo "Fee: " . $this->fee;
echo parent::$type;
}
}
Since PersonDetail()
method displays information itself, you don't need to return its value. It is enough just to call it in this case:
function StudentDetail() {
if(parent::$type === "Student") {
parent::PersonDetail(); // this will echo parent output
// and this code will still be executed
echo "Education Standard: " . $this->standard;
echo "Subjects: " . $this->subjects;
echo "Fee: " . $this->fee;
echo parent::$type;
}
}
In case of this question this is irrelevant, but sometimes the execution proceeds even after a function has returned, e.g in finally
clause
Upvotes: 3