在PHP中,我们要善于使用类型声明

这篇文章的目的是什么?

为了编写优雅的代码,了解这些是必要的。

类的属性

class Test
{
    public string $log;
}

类的常量

class Test
{
    public const string TEST = "Test";
}

函数的参数 de

function test(string $param)
{
    return $param . ' test';
}

函数的返回值

function test($param): string
{
    return $param . ' test';
}

多个声明

function test(string|int $param)
{
    return $param . ' test';
}

可为空的类型

function test($param): ?string
{
    return $param . ' test';
}

混合的模式 de

function test($param): ?mixed
{
    return $param . ' test';
}

结束

为了熟练掌握使用方法,我们需要理解继承时的行为以及使用trait的行为等等。为了编写易读的代码,学习并掌握这些知识会很有帮助,不是吗?