PHP 7引入了返回类型声明.这意味着我现在可以指示返回值是某个类,接口,数组,可调用或新的可阻塞标量类型之一,这对于函数参数是可能的.
function returnHello(): string {
return 'hello';
}
Run Code Online (Sandbox Code Playgroud)
通常情况下,值并不总是存在,并且您可能返回某种类型的某些内容,或者返回null.虽然您可以通过将其默认值设置为null(DateTime $time = null)来使参数可为空,但似乎没有办法为返回类型执行此操作.确实如此,或者我不知道怎么做?这些不起作用:
function returnHello(): string? {
return 'hello';
}
function returnHello(): string|null {
return 'hello';
}
Run Code Online (Sandbox Code Playgroud) 也许我错过了一些东西,但有没有选项来定义该函数应该有参数或返回例如User对象的数组?
请考虑以下代码:
<?php
class User
{
protected $name;
protected $age;
/**
* User constructor.
*
* @param $name
*/
public function __construct(string $name, int $age)
{
$this->name = $name;
$this->age = $age;
}
/**
* @return mixed
*/
public function getName() : string
{
return $this->name;
}
public function getAge() : int
{
return $this->age;
}
}
function findUserByAge(int $age, array $users) : array
{
$result = [];
foreach ($users as $user) {
if ($user->getAge() == $age) {
if ($user->getName() …Run Code Online (Sandbox Code Playgroud) 当我使用new这样定义类的对象时
$blah = new Whatever();
Run Code Online (Sandbox Code Playgroud)
我得到$ blah的自动完成功能.但是当我将$ blah作为函数参数时,我该怎么做呢?没有自动填充我不完整.
编辑:如果它在一个包含和PDT或Netbeans无法解决它怎么办?有没有办法在PHP中声明变量的类型?
php ×3
php-7 ×2
type-hinting ×2
arrays ×1
autocomplete ×1
netbeans ×1
nullable ×1
oop ×1
return-type ×1