PHP - Force function parameter to integer(PHP - 强制函数参数为整数)
问题描述
在 PHP 中你可以做以下事情:
In PHP you can do the following thing:
class Something {// bla bla}
function functionName(Something $object) {
// Do stuff here ^^^^^^^^^
}
这确保函数接收到Something类的实例.
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);
这表示 $someInt 是不是整数的实例,给定的整数"(我的 PHP 版本低于 7.0).如何强制执行基本类型?
This says that $someInt is "not an instance of integer, integer given" (with my PHP version below 7.0). How can you enforce to a basic type?
推荐答案
您不能在 PHP 中键入提示标量类型.唯一的机会是使用包装器类型.为此,SPL 库附带了 SplInt.
You can't typehint scalar types in PHP. The only chance is to use a wrapper type. The SPL library ships with SplInt for that purpose.
更新:看起来 PHP 7 提供了该功能.唉,时代变了:)
Update: Looks like PHP 7 offers that feature. Sigh, times changed :)
这篇关于PHP - 强制函数参数为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PHP - 强制函数参数为整数
基础教程推荐
- PHP 类:全局变量作为类中的属性 2021-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- 如何替换eregi() 2022-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
