PHP中的类型约束

*文
发布: 2023-03-18 15:34:01
原创
1559 人浏览过

本文主要介绍了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(&#39;print_r&#39;, 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  =  &#39;Try to cast a string value for fun&#39; ;
} catch ( UnexpectedValueException $uve ) {
    echo  $uve -> getMessage () .  PHP_EOL ;
}
 
echo  $int  .  PHP_EOL ;
/*
运行结果:
Value not an integer
94
*/
登录后复制

SPL Types会降低一定的灵活性和性能,实际项目中三思而行。

相关推荐:

PHP 数据类型和判断变量类型

PHP 函数注意

一些被忽视的 PHP 函数(整理)

以上是PHP中的类型约束的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!