Search code examples
phpreturn-typetype-hinting

Difference between :self and ClassName when type hinting return type


In PHP, when I specify a return type for a method that is supposed to return an instance of the class, I can do so like this:

class Foo  {
    public function bar(): self  { ... }
}

or:

class Foo  {
    public function bar(): Foo  { ... }
}

both seem to produce the same results / behavior.

What's the difference? Is one best practice over the other?

Thanks.


Solution

  • What's the difference?

    There is no difference. self is a keyword that refers to the class itself.

    You can think of it as an alternative name of the class being defined, thus in your example self is an alternative name of Foo. In other words, you can use self to replace Foo wherever you want, except right after the class keyword, of course.

    Here is an example:

    class Foo {
        const HELLO = 'Hello!';
    
        public function bar(): Foo {
            echo Foo::HELLO;
            return new Foo;
        }
    }
    

    Which is exactly the same as this:

    class Foo {
        const HELLO = 'Hello!';
    
        public function bar(): self {
            echo self::HELLO;
            return new self;
        }
    }
    

    Is one best practice over the other?

    No. Simply use whichever is most convenient or most useful to you.

    I usually prefer to use self so that if I need to rename the class, I only need to rename it in one place (right after class).