📄 19c02-2.php
字号:
<?php// Extend the Exception class to create a 'less than' exceptionclass LessThanException extends Exception { // Create a variable to hold what the minimum number was: private $number; // Redefine the constructor to just accept the number. public function __construct($num) { // First save the number off $this->number = $num; // Now we need to call the parent constructor and pass on data parent::__construct("Number was less than {$num}"); }}// Now also create a very similar Greater Than version:class GreaterThanException extends Exception { // Create a variable to hold what the max number was: private $number; // Redefine the constructor to just accept the number. public function __construct($num) { // Save the number off $this->number = $num; // Now we need to call the parent constructor and pass on data parent::__construct("Number was greater than {$num}"); } // Declare a function that will return what the number was: public function thanWhat() { return $this->number; }}// Now we can begin using these:// Begin a try block so that we can catch any exceptions that happen:try { // Generate a random number from 10 to 50 $num = rand(10,50); // If the number is less than 25 we aren't happy: if ($num < 25) { // Ok, it was less than, so throw a less than exception: throw new LessThanException(25); } // Also the number shouldn't be greater than 42 if ($num > 42) { // This time use the greater than exception. throw new GreaterThanException(42); }}// First try to catch less than errors:catch (LessThanException $le) { // We caught the exception, this is really unacceptable, so error out: die('<p>LESS THAN ERROR: ' . $le->getMessage() . "</p>\n");}// Now let's try to catch the greater than errors:catch (GreaterThanException $ge) { // If it was greater than, let's just invisibly reset it to what our // max really was: $num = $ge->thanWhat();}// We are happy with the number now so print it out.echo "<p>Our new number is: {$num}</p>\n";?>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -