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