PHP - 强制函数参数为整数 [英] PHP - Force function parameter to integer

查看:182
本文介绍了PHP - 强制函数参数为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PHP中,您可以执行以下操作:

  class Something {// bla bla} 

function functionName(Something $ object){
//在这里做的东西^^^^^^^^^
}

这可以确保函数接收到Something类的实例。



我的问题是我想强制执行一个基本类型。

 函数functionName(integer $ someInt){
//在这里做东西^^^^^^^
}
functionName(5);

这表示$ someInt是不是整数的实例,给定的整数。你如何执行一个基本的类型?

解决方案

你不能对标量类型参见手册:

从那里:


类型提示不能用于标量类型,如int或string 。资源和特性也是不允许的。


但是您可以通过PHP 7访问: https://wiki.php.net/rfc/scalar_type_hints_v5


In PHP you can do the following thing:

class Something {// bla bla}

function functionName(Something $object) {
    // Do stuff here  ^^^^^^^^^
}

This ensures that function received an instance of Something class.

My problem is that I want to enforce to a basic type.

function functionName(integer $someInt) {
    // Do stuff here  ^^^^^^^
}
functionName(5);

This says that $someInt is "not an instance of integer, integer given". How can you enforce to a basic type?

解决方案

You can't do this for scalar types see the manual:

And a quote from there:

Type hints cannot be used with scalar types such as int or string. Resources and Traits are not allowed either.

But you will be able to to this with PHP 7: https://wiki.php.net/rfc/scalar_type_hints_v5

这篇关于PHP - 强制函数参数为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆