Skip to content

Handle side effects of constructor calls #1205

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 2 commits into from
Apr 13, 2022

Conversation

VasekPurchart
Copy link
Contributor

@VasekPurchart VasekPurchart commented Apr 12, 2022

Fixes this original problem: https://phpstan.org/r/9800c2a7-080a-4d22-aeb9-802cd3cd8ce3 - if you pass a property into constructor, you do not know, what happens with it there and of course the state can be changed as in any other method where you pass an object. Marking the constructor as impure does not help: https://phpstan.org/r/e942d9a8-c20a-4b7d-973a-6bca67b5d69b .

Since you cannot return a value from a constructor, all constructors should be impure by the definition from https://phpstan.org/blog/remembering-and-forgetting-returned-values:

Pure function always returns the same value if its inputs (object state and arguments) are the same, and has no side effects. Impure function has side effects and its return value might change even if the input does not.

Question is whether that is practical default in regards to the code which calls the constructors - probably most of them do not change passed arguments.

There is a possibility to invalidate only with explicit impure annotation - but then this would behave differently than all of the other cases.

@VasekPurchart
Copy link
Contributor Author

VasekPurchart commented Apr 13, 2022

Until now constructors were evaluated as having side effects they were if not marked explicitly as pure. But also new constructor "calls" were not evaluated for side effects - causing the outlined issue.

Result of private discussion:

  • We cannot evaluate constructors as having side effects by default, it would be too harsh (as suggested in the first post).
  • To mark constructor as having side effects (and invalidate its arguments) it will be needed to mark it as impure with annotation.
  • Calls to constructor should still invalidate $this (see Parent constructor calls don't reset field type assumptions phpstan#4351 + original solution: c8174d5)

@VasekPurchart VasekPurchart marked this pull request as ready for review April 13, 2022 14:37
@ondrejmirtes ondrejmirtes merged commit 800f59c into phpstan:1.6.x Apr 13, 2022
@ondrejmirtes
Copy link
Member

Thank you!

@VasekPurchart VasekPurchart deleted the impure-constructor branch April 13, 2022 15:37
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.

2 participants