- πΊπΈUnited States xjm
I think the hypothesized performance aspect of this is needless micro-optimization. (That said, the addition to the call stack is unnecessary.)
The reason not to use
sprintf()
-- and the reason we've avoided it historically -- is that it adds absolutely no value over simply using a double-quoted string. Compare:-
"A string with $bar, {$foo['a']}, $baz, $a and $c, plus also $b embedded";
-
sprintf("A string with %s, %s, %s, %s and %s, plus also %s embedded", $bar, {$foo['a']}, $baz, $a, $c, $b);
The first is much closer to natural language. The second is significantly longer and les readable, plus it's easy to lose track of which
%s
refers to what.The only debatable case is if something requires concatenation (e.g. a function call is used), and even then, I find
sprintf()
makes it less readable. In those cases, defining a local variable with the function call (and thus avoiding concatenation in favor of something that reads like natural language) is probably a more desirable alternative than either concatenation orsprintf()
. -
- πΊπΈUnited States xjm
Updated the IS to de-emphasize the micro-optimization in favor of the readability aspects.
- π¦πΊAustralia mstrelan
I've been looking for a rector rule or phpcs sniff for this but can only find the inverse.
- EncapsedStringsToSprintfRector
- Squiz.Strings.DoubleQuoteUsage.ContainsVar
- SlevomatCodingStandard.Strings.DisallowVariableParsing
Whereas phpstorm has the Convert a 'sprintf()' call to string interpolation intention.
For implementation it would be good to find a way to automate this.
- π¬π§United Kingdom longwave UK
The simple cases with bare variable names in #13 are fine for interpolation, but when it comes to interpolating the results of method calls or deep array structures I personally prefer the sprintf style.
To me there is no single best option here and we should have some flexibility on this, and therefore I think this is won't fix.
- π§π¬Bulgaria pfrenssen Sofia
I vote for won't fix. We shouldn't gatekeep functions from the standard library.
- πΊπΈUnited States xjm
We "gatekeep" functional PHP code all the time; that's what coding standards are.
Regarding performance, https://git.drupalcode.org/project/drupal/-/merge_requests/5166/diffs has a comment contradicting the above.
- π¦πΊAustralia larowlan π¦πΊπ.au GMT+10
Moving this to the coding standards project where decisions about policies/standards like this live.
Tagging for needing issue summary update as there is a prescribed format for coding standards issues β
My 2c, simple variables should use pure string literals with variables as required (ie
"Something $wicked this {$way['comes']}"
) and sprintf if there are expressions or functionssprintf('Something %s this way %s, $wicked, $way->comes())