PHP - 强制函数参数为整数

2021-12-29 00:00:00 function parameters 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 :)

相关文章