gpt4 book ai didi

PHP类型提示原始值?

转载 作者:IT老高 更新时间:2023-10-28 11:56:38 27 4
gpt4 key购买 nike

我想知道是否可以对一种方法进行类型提示以期望原始类型?

类似这样的:

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

或者:

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

和你一样:

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

在 php 中可以吗?

最佳答案

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

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/en/functions.arguments.php#functions.arguments.type-declaration


当被问及这个答案时,PHP 5 是最新的,并说如下:

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.

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类型提示原始值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5724677/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com