Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/263.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/cmake/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
需要特定类型内聚的PHP_Php_Casting - Fatal编程技术网

需要特定类型内聚的PHP

需要特定类型内聚的PHP,php,casting,Php,Casting,在下面的代码中,$quantity被假定为一个整数,但我并没有做任何检查来要求它是整数 public function addProduct($product, $quantity) { 下面的代码要求它是一个整数,但如果$quantity='1'它将失败,因为它是一个字符串。我是否可以强制$quantity在此函数中作为整数执行,还是必须执行$object->addProduct($product,(int)$quantity) public function addProduct($pro

在下面的代码中,$quantity被假定为一个整数,但我并没有做任何检查来要求它是整数

public function addProduct($product, $quantity) {
下面的代码要求它是一个整数,但如果
$quantity='1'它将失败,因为它是一个字符串。我是否可以强制
$quantity
在此函数中作为整数执行,还是必须执行
$object->addProduct($product,(int)$quantity)

public function addProduct($product, int $quantity) {

最后,我是否可以将$product标记为字符串或整数,但如果它传递了一个对象,它将中断(不写入
is_object()
检查)

您必须将参数的类型指定为对象或数组,ie不能同时为->

您必须将参数的类型指定为对象或数组,ie不能同时为->

类型提示不适用于基元类型。在这种情况下,唯一的解决方案是在参数上使用intval()或is_int():

public function addProduct($product, $quantity) {
 $quantity = intval($quantity);
}

类型提示不适用于基元类型。在这种情况下,唯一的解决方案是在参数上使用intval()或is_int():

public function addProduct($product, $quantity) {
 $quantity = intval($quantity);
}

您可以在方法本身内强制转换值

$quantity = (int) $quantity;

您可以在方法本身内强制转换值

$quantity = (int) $quantity;

要确保param作为整数输入,只需在方法的开头添加以下行:

public function addProduct($product, $quantity) {
  $quantity = intval( $quantity );

  // your code here
}

要确保param作为整数输入,只需在方法的开头添加以下行:

public function addProduct($product, $quantity) {
  $quantity = intval( $quantity );

  // your code here
}

将类型强制转换为整数。您应该始终为所有用户输入的值强制转换为适当的数据类型

$quantity = (int) $quantity;

$quantity
现在是整数

您将类型强制转换为整数。您应该始终为所有用户输入的值强制转换为适当的数据类型

$quantity = (int) $quantity;
$quantity
现在是一个整数

的可能副本