PHP中的類型約束介紹
PHP的類方法和函數(shù)中可實現(xiàn)類型約束,但參數(shù)只能指定類、數(shù)組、接口、callable 四種類型,參數(shù)可默認為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();
//函數(shù)調(diào)用的參數(shù)與定義的參數(shù)類型不一致時,會拋出一個可捕獲的致命錯誤。
$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擴展實現(xiàn)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會降低一定的靈活性和性能,實際項目中三思而行。
相關文章
thinkphp隱藏index.php/home并允許訪問其他模塊的實現(xiàn)方法
這篇文章主要介紹了thinkphp隱藏index.php/home并允許訪問其他模塊的實現(xiàn)方法,想要達成的效果很簡單,我有兩個模塊,Home、Wechat。具體詳情請參考下本文。感興趣的朋友一起看看吧2016-10-10php正則去除網(wǎng)頁中所有的html,js,css,注釋的實現(xiàn)方法
下面小編就為大家?guī)硪黄猵hp正則去除網(wǎng)頁中所有的html,js,css,注釋的實現(xiàn)方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-11-11php中重定向網(wǎng)頁跳轉(zhuǎn)方法總結案例教程
這篇文章主要介紹了php中重定向網(wǎng)頁跳轉(zhuǎn)方法總結案例教程,本篇文章通過簡要的案例,講解了該項技術的了解與使用,以下就是詳細內(nèi)容,需要的朋友可以參考下2021-08-08thinkphp5框架實現(xiàn)數(shù)據(jù)庫讀取的數(shù)據(jù)轉(zhuǎn)換成json格式示例
這篇文章主要介紹了thinkphp5框架實現(xiàn)數(shù)據(jù)庫讀取的數(shù)據(jù)轉(zhuǎn)換成json格式,涉及thinkPHP5數(shù)據(jù)庫讀取數(shù)據(jù)與json格式轉(zhuǎn)換相關操作技巧,需要的朋友可以參考下2019-10-10PHP+Ajax異步通訊實現(xiàn)用戶名郵箱驗證是否已注冊( 2種方法實現(xiàn))
在網(wǎng)站注冊用戶時使用,主要為了無刷新異步驗證用戶輸入的用戶名或者Email是否已注冊。2011-12-12