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.
There is no difference between the two.
However, if you want something similar but different, use :static
(Requires PHP 8.0 and above). The difference is that returning class name, as in this case Foo
will return the particular class returned (not the child class) while returning static
will return the class the object was instantiated from (even if it's a child of the class where the method was defined).
For instance,
class Foo
{
public function bar(): static { ... }
public function rab(): Foo { ... }
}
class BabyFoo extends Foo
{
}
$instance = new BabyFoo();
In the code snippet above, $instance->bar()
will return BabyFoo
while $instance->rab()
will return Foo
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
).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.