《PHP實戰:PHP中的類型約束介紹》要點:
本文介紹了PHP實戰:PHP中的類型約束介紹,希望對您有用。如果有疑問,可以聯系我們。
PHP應用PHP的類辦法和函數中可實現類型約束,但參數只能指定類、數組、接口、callable 四種類型,參數可默認為NULL,PHP并不能約束標量類型或其它類型.
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();
PHP應用那么對于標量類型如何約束呢?
PHP應用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
*/
PHP應用SPL Types會降低必定的靈活性和性能,實際項目中三思而行.
維易PHP培訓學院每天發布《PHP實戰:PHP中的類型約束介紹》等實戰技能,PHP、MYSQL、LINUX、APP、JS,CSS全面培養人才。
轉載請注明本頁網址:
http://www.snjht.com/jiaocheng/10916.html