PHP类型提示到原始值? [英] PHP type-hinting to primitive values?

查看:94
本文介绍了PHP类型提示到原始值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以通过一种类型提示的方法来期望原始类型?

I'd like to know whether one can type-hint a method to expect primitive types?

类似这样的东西:

public function someMethod(string $str)
                         //^^^^^^

或者:

private function anotherMethod(int $num)
                             //^^^

与您使用的方法相同:

private function otherMethod(Person $rambo)
                           //^^^^^^

在php中有可能吗?

推荐答案

在PHP 7中,他们添加了以下内容:

In PHP 7 they added the following:

类型声明允许函数在调用时要求参数为某种类型.如果给定的值类型不正确,则会生成错误:在PHP 5中,这将是可恢复的致命错误,而PHP 7将引发TypeError异常.

Type declarations allow functions to require that parameters are of a certain type at call time. If the given value is of the incorrect type, then an error is generated: in PHP 5, this will be a recoverable fatal error, while PHP 7 will throw a TypeError exception.

参考: http://php.net/manual/zh/functions .arguments.php#functions.arguments.type-declaration

当询问此答案时,PHP 5是最新版本,并表示以下内容:

When this answer was asked, PHP 5 was the latest and said the following:

PHP 5引入了类型提示.现在,函数可以强制参数成为对象(通过在函数原型中指定类的名称),接口,数组(自PHP 5.1起)或可调用(自PHP 5.4起).但是,如果将NULL用作默认参数值,则以后的任何调用都将其允许作为参数.

PHP 5 introduces type hinting. Functions are now able to force parameters to be objects (by specifying the name of the class in the function prototype), interfaces, arrays (since PHP 5.1) or callable (since PHP 5.4). However, if NULL is used as the default parameter value, it will be allowed as an argument for any later call.

如果将类或接口指定为类型提示,则也允许其所有子级或实现.

If class or interface is specified as type hint then all its children or implementations are allowed too.

类型提示不能与int或string之类的标量类型一起使用.也不允许使用资源和特征.

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

参考: http://php.net/manual/en/language. oop5.typehinting.php

这篇关于PHP类型提示到原始值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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