本文主要介紹了PHP中的類型約束介紹,PHP的類方法和函數中可實作類別型約束,但參數只能指定類、數組、介面、callable 四種類型,參數可預設為NULL,PHP並不能約束標量類型或其它類型。希望本文對大家有所協助。
PHP的類方法和函數中可實作類別型約束,但參數只能指定類、數組、介面、callable 四種類型,參數可預設為NULL,PHP並不能約束標量類型或其它類型。
如下樣本:
<?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 integer94*/
SPL Types會降低一定的靈活性和效能,實際項目中三思而行。
相關推薦:
PHP 資料類型和判斷變數類型
PHP 函數注意
一些被忽視的 PHP 函數(整理)