类型约束

PHP 可以在类中使用类型约束。参数和返回值可以指定必须为对象(在函数原型里面指定类的名字),接口,数组或者可调用类型等等。不过如果使用 NULL 作为参数的默认值,那么在调用函数的时候依然可以使用 NULL 作为参数。如果一个类或接口指定了类型约束,则其所有的子类或实现也都如此。

<?php

class Foo
{
    /**
     * Return a string.
     *
     * @param  string $string
     * @return string
     */
    public function method(string $string): string
    {
        return $string;
    }
}

class Bar extends Foo
{
    //
}

$foo = new Foo();
var_dump($foo->method('foo')); // string(3) "foo"

$bar = new Bar();
var_dump($bar->method(0));     // string(1) "0"

results matching ""

    No results matching ""