PHP 需要特定类型凝聚力
在下面的代码中, $quantity 被假定为一个整数,但我没有对其进行任何检查以要求它如此。
public function addProduct($product, $quantity) {
下面的代码要求它是一个整数,但是如果 $quantity = '1';
它将失败,因为它是一个字符串。我是否可以强制 $quantity
在这个函数中作为整数出现,或者我必须这样做 $object->addProduct($product, (int) $quantity );
?
public function addProduct($product, int $quantity) {
最后,我是否可以将 $product 标记为字符串或整数,但如果它传递了一个对象,它就会中断(无需编写 is_object()
检查)
With the below code, $quantity is assumed to be an integer but I'm not doing any checking against it to require it to be so.
public function addProduct($product, $quantity) {
The below code will require it to be an integer, BUT if $quantity = '1';
it'll fail because it's a string. Is it possible for me to force $quantity
to come through as an integer in this function, or do I HAVE to do $object->addProduct($product, (int) $quantity);
?
public function addProduct($product, int $quantity) {
Lastly, is it possible for me to flag $product as either a string or an integer, but if it's passed an object it'll break (without writing an is_object()
check)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
类型提示不适用于原始类型。在这种情况下,您唯一的解决方案是在 param 上使用 intval() 或 is_int() :
Type hinting is not available for primitive type. The only solution you have in this case is to use intval() or is_int() on your param :
您必须将参数的类型指定为对象或数组,即它不能同时是 -> http://php.net/manual/en/language.oop5.typehinting.php
You must specify the type of an argument as either an Object or an Array, ie it cant be both -> http://php.net/manual/en/language.oop5.typehinting.php
为了确保参数以整数形式输入,只需在方法的开头添加这一行:
To make sure that param gets in as an integer, simply add this line at the very begining of your method:
您可以在方法本身内转换该值
You can cast the value within the method itself
您将类型转换为整数。您应该始终将所有用户输入的值转换为适当的数据类型。
$quantity
现在是一个整数You cast the type to an integer. You should always cast to the appropriate data type for all your user-inputted values.
$quantity
is now an integer