Below you will find pages that utilize the taxonomy term “PHPStan”
A step-debugger for the PHP AST
When you’re learning to write custom rules for PHPStan or Rector, you’ll have to learn more about the PHP programming language as well. To be more precise, about the way the interpreter parses PHP code. The result of parsing PHP code is a tree of nodes which represents the structure of the code, e.g. you’ll have a Class definition node, a Method definition node, and within those method Statement nodes, and so on. Each node can be checked for errors (with PHPStan), or automatically refactored in some way (with Rector).
Effective immutability with PHPStan
This article is about a topic that didn’t make the cut for my latest book, Recipes for Decoupling. It still contains some useful ideas I think, so here it is anyway!
DateTimeImmutable is mutable
I don’t know where I first heard it, but PHP’s DateTimeImmutable
is not immutable:
<?php
$dt = new DateTimeImmutable('now');
echo $dt->getTimestamp() . "\n";
$dt->__construct('tomorrow');
echo $dt->getTimestamp() . "\n";
The result:
1656927919
1656972000
Indeed, DateTimeImmutable
is not really immutable because its internal state can be modified after instantiation. After calling __construct()
again, any existing object reference will have the modified state as well. But an even bigger surprise might be that if a constructor is public
, it’s just another method that you can call. You’re not supposed to, but you can. Which is another reason to make the constructor of non-service objects private
and add a public static constructor to a class that you want to be immutable: