<?php
//创建可抛出一个异常的函数
function checkNum($number)
{
if($number>1)
{
throw new Exception("Value must be 1 or below");
}
return true;
}
//在 "try" 代码块中触发异常
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 $e**)
{
echo 'Message: ' .$e->getMessage();
}
?>
php是弱类型语言,catch中为什么要写exception $e ,而不是直接写$e
<?php
//创建可抛出一个异常的函数
function checkNum($number)
{
if($number>1)
{
throw new Exception("Value must be 1 or below");
}
return true;
}
//在 "try" 代码块中触发异常
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 $e**)
{
echo 'Message: ' .$e->getMessage();
}
?>
php是弱类型语言,catch中为什么要写exception $e ,而不是直接写$e
异常本来就是以类型为基础的啊
PHP5开始, 可以对函数参数进行类型约束: http://php.net/manual/zh/language.oop5.typehinting.php
<?php
//如下面的类
class MyClass
{
/**
* 测试函数
* 第一个参数必须为类OtherClass的一个对象
*/
public function test(OtherClass $otherclass) {
echo $otherclass->var;
}
/**
* 另一个测试函数
* 第一个参数必须为数组
*/
public function test_array(array $input_array) {
print_r($input_array);
}
}
//另外一个类
class OtherClass {
public $var = 'Hello World';
}
类型约束只支持对象 和 数组(php 5.1之后)两种类型。而不支持整型 和 字符串类型。
对,有点像java
立即学习“PHP免费学习笔记(深入)”;
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
C++高性能并发应用_C++如何开发性能关键应用
Java AI集成Deep Java Library_Java怎么集成AI模型部署
Golang后端API开发_Golang如何高效开发后端和API
Python异步并发改进_Python异步编程有哪些新改进
C++系统编程内存管理_C++系统编程怎么与Rust竞争内存安全
Java GraalVM原生镜像构建_Java怎么用GraalVM构建高效原生镜像
Python FastAPI异步API开发_Python怎么用FastAPI构建异步API
C++现代C++20/23/26特性_现代C++有哪些新标准特性如modules和coroutines
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号