Confused about type hinting in PHP

时间:2019-04-16 23:28:19

标签: php

So consider the following example:

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

Now lets implement this:

class ViewBuilder implements ViewBuilderContract {

    private $formNames = [];

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

        return $this;
    }
}

As far as the docs are concerned:

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.

Thats what I am doing by returning $this - according to the docs.

But when I run:

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

I get, which you can see here - click execute code:

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

Which doesn't make sense according to the docs. It should be a valid return. Do I just remove self? And if so why? and is there a way to stipulate a return value?

1 个答案:

答案 0 :(得分:1)

You can't specify self is returned in an interface. See this answer for more information.

You could instead specify that the function return a ViewBuilderContract:

<?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;
        }
    }

Sandbox here