PHP中的类型约束介绍,PHP类型约束介绍
PHP的类方法和函数中可实现类型约束,但参数只能指定类、数组、接口、callable 四种类型,参数可默认为NULL,PHP并不能约束标量类型或其它类型。
如下示例:
复制代码 代码如下:
class Test
{
public function test_array(array $arr)
{
print_r($arr);
}
public function test_class(Test1 $test1 = null)
{
print_r($test1);
}
public function test_callable(callable $callback, $data)
{
call_user_func($callback, $data);
}
public function test_interface(Traversable $iterator)
{
print_r(get_class($iterator));
}
public function test_class_with_null(Test1 $test1 = NULL)
{
}
}
class Test1{}
$test = new Test();
//函数调用的参数与定义的参数类型不一致时,会抛出一个可捕获的致命错误。
$test->test_array(array(1));
$test->test_class(new Test1());
$test->test_callable('print_r', 1);
$test->test_interface(new ArrayObject(array()));
$test->test_class_with_null();
那么对于标量类型如何约束呢?
PECL扩展库中提供了SPL Types扩展实现interger、float、bool、enum、string类型约束。
复制代码 代码如下:
$int = new SplInt ( 94 );
try {
$int = 'Try to cast a string value for fun' ;
} catch ( UnexpectedValueException $uve ) {
echo $uve -> getMessage () . PHP_EOL ;
}
echo $int . PHP_EOL ;
/*
运行结果:
Value not an integer
94
*/
SPL Types会降低一定的灵活性和性能,实际项目中三思而行。

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

Atom Editor Mac 버전 다운로드
가장 인기 있는 오픈 소스 편집기

VSCode Windows 64비트 다운로드
Microsoft에서 출시한 강력한 무료 IDE 편집기

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

DVWA
DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는
