php为什么可以忽略类型转换,为什么类型转换不是PHP函数参数中的一个选项

PHP确实有一个

rudimentary type-hinting ability用于数组和对象,但它不适用于标量类型.

PHP 5 introduces type hinting. Functions are now able to force parameters to be objects (by specifying the name of the class in the function prototype), interfaces, arrays (since PHP 5.1) or callable (since PHP 5.4). However, if NULL is used as the default parameter value, it will be allowed as an argument for any later call.

If class or interface is specified as type hint then all its children or implementations are allow>ed too.

Type hints can not be used with scalar types such as int or string. Traits are not allowed either.

数组提示示例:

public function needs_array(array $arr) {

var_dump($arr);

}

对象提示示例

public function needs_myClass(myClass $obj) {

var_dump($obj);

}

如果需要强制执行标量类型,则需要通过类型转换或检查函数中的类型以及如果收到错误类型而挽救或采取相应行动.

如果输入错误,则抛出异常

public function needs_int_and_string($int, $str) {

if (!ctype_digit(strval($int)) {

throw new Exception('$int must be an int');

}

if (strval($str) !== $str) {

throw new Exception('$str must be a string');

}

}

只是默默地对params进行类型化

public function needs_int_and_string($int, $str) {

$int = intval($int);

$str = strval($str);

}

更新:PHP 7添加标量类型提示

PHP 7引入了严格和非严格模式的Scalar type declarations.如果函数参数变量与声明的类型不完全匹配,或者以非严格模式强制类型,现在可以在严格模式下抛出TypeError.

declare(strict_types=1);

function int_only(int $i) {

// echo $i;

}

$input_string = "123"; // string

int_only($input);

// TypeError: Argument 1 passed to int_only() must be of the type integer, string given

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值