phpcs-variable-analysis icon indicating copy to clipboard operation
phpcs-variable-analysis copied to clipboard

Improve handling of initial values in initializers

Open jrfnl opened this issue 3 years ago • 1 comments

I noticed when fixing up the CS, that the VariableAnalysisSniff::processVariableAsStaticDeclaration() uses outdated assumptions on what can be part of an initial value:

// Are we a static declaration?
// Static declarations are a bit more complicated than globals, since they
// can contain assignments. The assignment is compile-time however so can
// only be constant values, which makes life manageable.

This is outdated due to:

  1. PHP 5.6: initializers can now contain constant expressions, i.e. sums, concatenation etc, as long as the values used are constant. Ref: https://wiki.php.net/rfc/const_scalar_exprs
  2. PHP 5.6: initializers can now contain constant arrays. Ref: https://www.php.net/manual/en/migration56.new-features.php#migration56.new-features.const-scalar-exprs (second code sample)
  3. PHP 8.1: as of PHP 8.1, new class instantiations are allowed in initializers, as long as any parameters passed evaluate to constant values. Ref: https://wiki.php.net/rfc/new_in_initializers

Aside from that, magic constants are also allowed (and have been for a long time): https://www.php.net/manual/en/language.constants.magic.php

For the record, "initializers" in this context are:

  1. Class constant declarations.
  2. Property declarations
  3. Default values for function parameters.
  4. Default values for variables declared via the static keyword.

I believe it would be good to review the code base to verify these situation are handled correctly in all relevant places.

jrfnl avatar Jun 02 '22 01:06 jrfnl

Related to #158

jrfnl avatar Jun 02 '22 02:06 jrfnl