养殖 - 种植 - 加工 - 创业 - 骗局 - 问答 - 百科 - 节气 - 民俗 - 手机版
您的当前位置: 致富创业网 > 养殖致富 > 黄颡鱼 > PHP中的类型约束介绍:常见的约束类型有哪些

PHP中的类型约束介绍:常见的约束类型有哪些

来源:黄颡鱼 时间:2018-08-16 点击:

这篇文章主要介绍了PHP中的类型约束介绍,PHP的类方法和函数中可实现类型约束,但参数只能指定类、数组、接口、callable 四种类型,参数可默认为NULL,PHP并不能约束标量类型或其它类型,需要的朋友可以参考

PHP的类方法和函数中可实现类型约束,但参数只能指定类、数组、接口、callable 四种类型,参数可默认为NULL,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 integer

94

*/

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

推荐访问:约束 类型 介绍 PHP中的类型约束介绍 工程中的约束类型 常见的约束类型

致富创业网 www.csyzzm.com

Copyright © 2002-2018 . 致富创业网 版权所有 湘ICP备12008529号-1

Top