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 - 强制函数参数为整数
基础教程推荐
- Web 服务器如何处理请求? 2021-01-01
- 主题化 Drupal 7 的 Ubercart “/cart"页 2021-01-01
- php中的PDF导出 2022-01-01
- 使用 scandir() 在目录中查找文件夹 (PHP) 2022-01-01
- php中的foreach复选框POST 2021-01-01
- 如何在数学上评估像“2-1"这样的字符串?产生“1"? 2022-01-01
- PHPUnit 的 Selenium 2 文档到底在哪里? 2022-01-01
- php 7.4 在写入变量中的 Twig 问题 2022-01-01
- Yii2 - 在运行时设置邮件传输参数 2022-01-01
- 将变量从树枝传递给 js 2022-01-01
