Dea*_*tem 6 php parameters types casting function
对于你们许多人来说这听起来像是一个愚蠢的问题,但它让我想知道为什么PHP不允许在其函数参数中进行类型转换.许多人使用此方法来转换为他们的参数:
private function dummy($id,$string){
echo (int)$id." ".(string)$string
}
Run Code Online (Sandbox Code Playgroud)
要么
private function dummy($id,$string){
$number=(int)$id;
$name=(string)$string;
echo $number." ".$name;
}
Run Code Online (Sandbox Code Playgroud)
但是看看许多其他编程语言,他们接受类型转换为他们的函数参数.但是在PHP中执行此操作可能会导致错误.
private function dummy((int)$id,(string)$string){
echo $id." ".$string;
}
Run Code Online (Sandbox Code Playgroud)
解析错误:语法错误,意外T_INT_CAST,期待'&'或T_VARIABLE
要么
private function dummy(intval($id),strval($string)){
echo $id." ".$string;
}
Run Code Online (Sandbox Code Playgroud)
解析错误:语法错误,意外'(',期待'&'或T_VARIABLE
只是想知道为什么这不起作用,如果有办法.如果没有办法,那么按照常规方式对我来说没问题:
private function dummy($id,$string){
echo (int)$id." ".(string)$string;
}
Run Code Online (Sandbox Code Playgroud)
Mic*_*ski 10
PHP确实对数组和对象具有基本的类型提示能力,但它不适用于标量类型.
PHP 5引入了类型提示.函数现在能够强制参数为对象(通过在函数原型中指定类的名称),接口,数组(自PHP 5.1起)或可调用(自PHP 5.4起).但是,如果将NULL用作默认参数值,则允许将其作为后续调用的参数.
如果将类或接口指定为类型提示,则其所有子项或实现也都是allow> ed.
类型提示不能与标量类型(如int或string)一起使用.也不允许特征.
public function needs_array(array $arr) {
var_dump($arr);
}
Run Code Online (Sandbox Code Playgroud)
public function needs_myClass(myClass $obj) {
var_dump($obj);
}
Run Code Online (Sandbox Code Playgroud)
如果需要强制执行标量类型,则需要通过类型转换或检查函数中的类型以及如果收到错误类型而挽救或采取相应行动.
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');
}
}
Run Code Online (Sandbox Code Playgroud)
public function needs_int_and_string($int, $str) {
$int = intval($int);
$str = strval($str);
}
Run Code Online (Sandbox Code Playgroud)
PHP 7引入了具有严格和非严格模式的标量类型声明.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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7527 次 |
| 最近记录: |