gpt4 book ai didi

php - 为什么类型转换不是 PHP 函数参数中的一个选项

转载 作者:可可西里 更新时间:2023-11-01 13:11:24 31 4
gpt4 key购买 nike

对于你们中的许多人来说,这听起来像是一个愚蠢的问题,但它让我想知道为什么 PHP 不允许在其函数参数中进行类型转换。许多人使用这种方法来转换到他们的参数中:

private function dummy($id,$string){
echo (int)$id." ".(string)$string
}

或者

private function dummy($id,$string){
$number=(int)$id;
$name=(string)$string;
echo $number." ".$name;
}

但是看看许多其他编程语言,它们接受类型转换到它们的函数参数中。但是在 PHP 中这样做可能会导致错误。

private function dummy((int)$id,(string)$string){
echo $id." ".$string;
}

Parse error: syntax error, unexpected T_INT_CAST, expecting '&' or T_VARIABLE

或者

private function dummy(intval($id),strval($string)){
echo $id." ".$string;
}

Parse error: syntax error, unexpected '(', expecting '&' or T_VARIABLE

只是想知道为什么这不起作用以及是否有办法。如果没有办法,那么走常规路对我来说就可以了:

private function dummy($id,$string){
echo (int)$id." ".(string)$string;
}

最佳答案

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');
}
}

静静地输入参数

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

关于php - 为什么类型转换不是 PHP 函数参数中的一个选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11479782/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com