所谓类型约束就是定义一个变量的时候,必须指定其类型,并且以后该变量也只能存储该类型数据。在这篇文章中,我将给大家介绍一下php类型约束以及用法。
php类型约束的介绍
PHP是弱类型语言,其特点就是无需为变量指定类型,而且在其后也可以存储任何类型,当然这也是使用PHP能快速开发的关键点之一。但是自PHP5起,我们就可以在函数(方法)形参中使用类型约束了。
函数的参数可以指定的范围如下:
1、必须为对象(在函数原型里面指定类的名字);
2、接口;
3、数组(PHP 5.1 起);
4、callable(PHP 5.4 起)。
5、如果使用 NULL 作为参数的默认值,那么在调用函数的时候依然可以使用 NULL 作为实参。
6、如果一个类或接口指定了类型约束,则其所有的子类或实现也都如此。
注意:在PHP7以前,类型约束不能用于标量类型如 int 或 string。Traits 也不允许。
php类型约束的用法:
下面是官方给的例子:
<?php //如下面的类 class MyClass { /** * 测试函数 * 第一个参数必须为 OtherClass 类的一个对象 */ public function test(OtherClass $otherclass) { echo $otherclass->var; } /** * 另一个测试函数 * 第一个参数必须为数组 */ public function test_array(array $input_array) { print_r($input_array); } } /** * 第一个参数必须为递归类型 */ public function test_interface(Traversable $iterator) { echo get_class($iterator); } /** * 第一个参数必须为回调类型 */ public function test_callable(callable $callback, $data) { call_user_func($callback, $data); } } // OtherClass 类定义 class OtherClass { public $var = 'Hello World'; } ?>
函数调用的参数与定义的参数类型不一致时,会抛出一个可捕获的致命错误。
<?php // 两个类的对象 $myclass = new MyClass; $otherclass = new OtherClass; // 致命错误:第一个参数必须是 OtherClass 类的一个对象 $myclass->test('hello'); // 致命错误:第一个参数必须为 OtherClass 类的一个实例 $foo = new stdClass; $myclass->test($foo); // 致命错误:第一个参数不能为 null $myclass->test(null); // 正确:输出 Hello World $myclass->test($otherclass); // 致命错误:第一个参数必须为数组 $myclass->test_array('a string'); // 正确:输出数组 $myclass->test_array(array('a', 'b', 'c')); // 正确:输出 ArrayObject $myclass->test_interface(new ArrayObject(array())); // 正确:输出 int(1) $myclass->test_callable('var_dump', 1); ?>
类型约束不只是用在类的成员函数里,也能使用在函数里:
<?php // 如下面的类 class MyClass { public $var = 'Hello World'; } /** * 测试函数 * 第一个参数必须是 MyClass 类的一个对象 */ function MyFunction (MyClass $foo) { echo $foo->var; } // 正确 $myclass = new MyClass; MyFunction($myclass); ?>
类型约束允许 NULL 值:
<?php /* 接受 NULL 值 */ function test(stdClass $obj = NULL) { } test(NULL); test(new stdClass); ?>
PHP7
标量类型声明 (PHP 7)
标量类型声明 有两种模式: 强制 (默认) 和 严格模式。
现在可以使用下列类型参数(无论用强制模式还是严格模式):
1、字符串(string),
2、整数 (int),
3、浮点数 (float),
4、布尔值 (bool)。
它们扩充了PHP5中引入的其他类型:类名,接口,数组和 回调类型。
<?php // 强制模式 function sumOfInts(int ...$ints) { return array_sum($ints); } var_dump(sumOfInts(2, '3', 4.1));
以上范例的运行结果会输出:int(9)
要使用严格模式,一个 declare 声明指令必须放在文件的顶部。这意味着严格声明标量是基于文件可配的。 这个指令不仅影响参数的类型声明,也影响到函数的返回值声明。
相关文章推荐:
php中类型约束的思路代码分享以上是php类型约束是什么?php类型约束简介和用法的详细内容。更多信息请关注PHP中文网其他相关文章!

TheSecretTokeEpingAphp-PowerEdwebSiterUnningSmoothlyShyunderHeavyLoadInVolvOLVOLVOLDEVERSALKEYSTRATICES:1)emplactopCodeCachingWithOpcachingWithOpCacheToreCescriptexecution Time,2)使用atabasequercachingCachingCachingWithRedataBasEndataBaseLeSendataBaseLoad,3)

你应该关心DependencyInjection(DI),因为它能让你的代码更清晰、更易维护。1)DI通过解耦类,使其更模块化,2)提高了测试的便捷性和代码的灵活性,3)使用DI容器可以管理复杂的依赖关系,但要注意性能影响和循环依赖问题,4)最佳实践是依赖于抽象接口,实现松散耦合。

是的,优化papplicationispossibleandessential.1)empartcachingingcachingusedapcutorediucedsatabaseload.2)优化的atabaseswithexing,高效Quereteries,and ConconnectionPooling.3)EnhanceCodeWithBuilt-unctions,避免使用,避免使用ingglobalalairaiables,并避免使用

theKeyStrategiestosiminificallyBoostphpapplicationPermenCeare:1)useOpCodeCachingLikeLikeLikeLikeLikeCacheToreDuceExecutiontime,2)优化AtabaseInteractionswithPreparedStateTemtStatementStatementSandProperIndexing,3)配置

aphpdepentioncontiveContainerIsatoolThatManagesClassDeptions,增强codemodocultion,可验证性和Maintainability.itactsasaceCentralHubForeatingingIndections,因此reducingTightCightTightCoupOulplingIndeSingantInting。

选择DependencyInjection(DI)用于大型应用,ServiceLocator适合小型项目或原型。1)DI通过构造函数注入依赖,提高代码的测试性和模块化。2)ServiceLocator通过中心注册获取服务,方便但可能导致代码耦合度增加。

phpapplicationscanbeoptimizedForsPeedAndeffificeby:1)启用cacheInphp.ini,2)使用preparedStatatementSwithPdoforDatabasequesies,3)3)替换loopswitharray_filtaray_filteraray_maparray_mapfordataprocrocessing,4)conformentnginxasaseproxy,5)

phpemailvalidation invoLvesthreesteps:1)格式化进行regulareXpressecthemailFormat; 2)dnsvalidationtoshethedomainhasavalidmxrecord; 3)


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

SublimeText3汉化版
中文版,非常好用

Dreamweaver Mac版
视觉化网页开发工具

SublimeText3 英文版
推荐:为Win版本,支持代码提示!