1<?PHP2 //define a student class3 classstudent{4 //Student's name5 Private $name;6 //The age of the student7 Private $age;8 9 Public function__construct ($name,$age){Ten One $this->setname ($name); A $this->setage ($age); - } - Public functionSetName ($name){ the $this->name=$name; - } - Public functionSetage ($age){ - if(Is_int($age) &&$age>18&&$age<25){ + $this->age=$age; -}Else{ + //throws an exception and logs which student is wrong A Throw NewStudentexception ($this,$this->name. ' Age error ', 333); at } - } - - } - //Customize a student exception class, - //When it's time to know which student is abnormal in classStudentexceptionextends Exception{ - to protected $student; + - //we need to rewrite the parent class's construction method the Public function__construct ($stu,$message,$code){ * //keep track of student information $ $this->student=$stu;Panax Notoginseng - //the above is easy to understand the //$this->message= $message; + //$this->code= $code; A the //Question some doubts about here + ///I understand the code this way: overriding the constructor of the parent class does not get the parent class value, when we need to initialize the parent class constructor method -Parent::__construct ($message,$code); $ } $ Public functiongetstudent () { - - return $this-student; the - }Wuyi } the //monitor all students and return the information if there is a student error - Try{ Wu $student 1=NewStudent (' AAA ', 21); - $student 2=NewStudent (' BBB ', 23); About $student 3=NewStudent (' CCC ', 19); $ $student 4=NewStudent (' DDD ', 28); - - } - Catch(studentexception$e){ A Echo"<pre>"; + //get all the information about the student who has the error the Var_dump($e-getstudent ()); - Echo"Error message occurred:".$e-getMessage (); $ } the?>
Use of the Try catch custom exception class