Skip to content

[12.x] when a method returns $this set the return type to static #56092

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 22, 2025

Conversation

browner12
Copy link
Contributor

while PHP is a little lenient here, the more accurate return type when returning $this is static, not self.

when returning new static() the return type should also be static over self.

this may be a little pedantic, but it should be slightly more accurate. also this is forward looking in case PHP ever decided to get more strict in their type checks regarding these return types.

while PHP is a little lenient here, the more accurate return type when returning `$this` is static, not self.

when returning `new static()` the return type should also be `static` over `self`.
@NickSdot
Copy link
Contributor

NickSdot commented Jun 21, 2025

If the return type of an overridden method in a child class is the explicit child class, this will cause an incompatible declaration error.

Before:
https://3v4l.org/iQc6R

After:
https://3v4l.org/fmclK

You might want to target master?

@taylorotwell taylorotwell merged commit 071a9d3 into laravel:12.x Jun 22, 2025
62 checks passed
@browner12
Copy link
Contributor Author

@NickSdot in your example, the fix would be for SomeChild->foo() to also return static as well, correct?

@browner12 browner12 deleted the AB-self-vs-static branch June 23, 2025 14:52
@NickSdot
Copy link
Contributor

@browner12 correct. Not a biggie. Just wanted to point out that this is breaking. Anyway, Taylor merged so never mind me. 😅

@browner12
Copy link
Contributor Author

Thanks for confirming.

Fingers crossed, this seems like a highly unlikely scenario, but thanks for pointing it out!

mohammad-fouladgar pushed a commit to mohammad-fouladgar/framework that referenced this pull request Jul 22, 2025
…l#56092)

while PHP is a little lenient here, the more accurate return type when returning `$this` is static, not self.

when returning `new static()` the return type should also be `static` over `self`.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants