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 - 强制函数参数为整数


- 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
- 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
- PHP foreach() 与数组中的数组? 2022-01-01
- 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 覆盖 Magento 社区模块控制器的问题 2022-01-01
- PHP - if 语句中的倒序 2021-01-01
- openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01
- Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01
- 如何在 Symfony2 中正确使用 webSockets 2021-01-01