php中catch条件的语法
在下面示例的catch语句中php中catch条件的语法,php,class,syntax,Php,Class,Syntax,在下面示例的catch语句中 那么$e有什么不同吗?如果不是,为什么我们在对象之前写类名。请解释一下语法 我试图寻找一些不同的语法来在php中声明类,但找不到类似的东西。这已经是一个异常实例,正在传递到catch块中。如果您正在声明自己的异常,它将如下所示: class TestException extends Exception { public function __construct($msg, $code = 0, Exception $previousException =
那么$e有什么不同吗?如果不是,为什么我们在对象之前写类名。请解释一下语法
我试图寻找一些不同的语法来在php中声明类,但找不到类似的东西。这已经是一个异常实例,正在传递到catch块中。如果您正在声明自己的异常,它将如下所示:
class TestException extends Exception
{
public function __construct($msg, $code = 0, Exception $previousException = null) {
parent::__construct($msg, $code, $previousException);
}
//How will it print if you just echo the class
public function __toString() {
return 'A test string';
}
}
//create function with an exception
function checkNum($number) {
if($number>1) {
throw new TestException("Value must be 1 or below");
}
return true;
}
try {
checkNum(2);
//If the exception is thrown, this text will not be shown
echo 'If you see this, the number is 1 or below';
}
//catch exception
catch(TestException $e) {
echo 'Message: ' .$e->getMessage();
}
$e是类Exception的对象。因此,对象也可以这样声明:它不是对象的声明。当您抛出异常时,您正在创建一个对象,并且该对象被传递到catch block catchException$ewe,在对象之前写入className,因为我们希望在$e中只接受异常类的实例,这是一种类型,暗示您可以了解更多有关它的信息
object_name = new class_name
class TestException extends Exception
{
public function __construct($msg, $code = 0, Exception $previousException = null) {
parent::__construct($msg, $code, $previousException);
}
//How will it print if you just echo the class
public function __toString() {
return 'A test string';
}
}
//create function with an exception
function checkNum($number) {
if($number>1) {
throw new TestException("Value must be 1 or below");
}
return true;
}
try {
checkNum(2);
//If the exception is thrown, this text will not be shown
echo 'If you see this, the number is 1 or below';
}
//catch exception
catch(TestException $e) {
echo 'Message: ' .$e->getMessage();
}