我创建了Person
类,然后将其扩展到Student
类。当我在Student
对象上调用方法时,它不能按预期工作。
这是我的代码
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();
仅打印PersonDetail()
,但不打印教育标准,科目和费用等完整信息。
这是我的输出
Person Number#1 details are given below:
Person Name: Muhammad Hamza Nisar
Person Gender: Male
Age: 22 years old
我还需要在其下方看到StudentDetail()
输出。怎么了?怎么解决?
答案 0 :(得分:3)
如果在函数(或方法)中放置return
语句,PHP将不会在此点之后继续执行(大部分时间)*。因此,当执行以下代码(取自您的问题)时,它会在您致电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;
}
}
由于PersonDetail()
方法本身会显示信息,因此您无需返回其值。在这种情况下只需调用它就足够了:
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;
}
}
在这个问题的情况下,这是无关紧要的,但有时即使在函数返回后执行仍在进行,例如finally
子句