对PHP中的类型提示感到困惑


Confused about type hinting in PHP

我认为:the following exampleP></

1
2
3
interface ViewBuilderContract {
    public function addFormName(string $formName): self;
}

本:我们实施"订单"P></

1
2
3
4
5
6
7
8
9
10
class ViewBuilder implements ViewBuilderContract {

    private $formNames = [];

    public function addFormName(string $formName): self {
        $this->formNames[] = $formName;

        return $this;
    }
}

as as the和关注的是:P></

self The parameter must be an instanceof the same class as the one the
method is defined on. This can only be used on class and instance
methods.

那是我做$this- AM模式校正根据to the docs。P></

但当运行:P></

1
(new ViewBuilder)->addFormName('sample');

我在这里,你可以看到它的尾巴:点击executeP></

Declaration of ViewBuilder::addFormName(string $formName): ViewBuilder
must be compatible with ViewBuilderContract::addFormName(string
$formName): ViewBuilderContract

which make the不感和根据。EN should be a valid返回。我只是selfremove呢?如果我知道为什么?and is there to编制方式的返回值?P></


不能在接口中指定返回self。有关详细信息,请参阅此答案。

您可以指定函数返回一个ViewBuilderContract

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
    interface ViewBuilderContract {
        public function addFormName(string $formName): ViewBuilderContract;
    }

    class ViewBuilder implements ViewBuilderContract {

        private $formNames = [];

        public function addFormName(string $formName): ViewBuilderContract {
            $this->formNames[] = $formName;

            return $this;
        }
    }

这里的沙盒