欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

PHP中的類型約束介紹

 更新時間:2015年05月11日 11:31:40   投稿:junjie  
這篇文章主要介紹了PHP中的類型約束介紹,PHP的類方法和函數(shù)中可實現(xiàn)類型約束,但參數(shù)只能指定類、數(shù)組、接口、callable 四種類型,參數(shù)可默認為NULL,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會降低一定的靈活性和性能,實際項目中三思而行。

相關文章

最新評論