PHP中的類型約束

來源:互聯網
上載者:User
本文主要介紹了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 函數(整理)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.