Re: [VOTE] Make compact function reports undefined passed variables
| From: | Rowan Collins | Date: | Sun, 10 Jun 2018 22:49:00 +0000 |
| Subject: | Re: [VOTE] Make compact function reports undefined passed variables | ||
| References: | 1 2 3 4 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-102220@lists.php.net to get a copy of this message | ||
On 10/06/2018 19:41, Hoffman, Zachary Robert wrote:
Deprecating compact() would hurt workflows where you use the same variable names several times in different contexts, even though they are only declared locally for the purposes of compact() itself.I am not convinced that building logic around variable names is ever a good thing. Variable names are primarily a label used by the programmer to write source code, and in my opinion that's all they should ever be. Programmers should be free to rename them within their scope, and compilers should be free to erase them when optimising a production build.
Your two classes here are clearly collaborating on the processing of some specific collection of values, which have something in common with each other; they are not really passing 4 variables, but some structure which has 4 fields. It might be nice in some cases if that could be a by-value "struct" type, but the most appropriate in current PHP would be to define a third class and pass an instance of that from class A to class B.public function c() { $d = $this->d(); $a = pow($d, $d + 1); $c = $a ^ 0b1100; $b = $a - $d;return new B( compact( $this->b() ) ); }
foreach (A::b() as $b) {This is a poor example, because if this was really the end result, then the two classes aren't even using the data with the same meaning, and class A might as well return a plain array - if the keys are no longer important, it could simply return [$a, $b, $c, $d].echo $a->a($b) . PHP_EOL;}
The alternative would be manipulating array elements directly, like this: public function c() {I agree that this is slightly harder to read (and the version I would prefer where $e was an object rather than an array would look similar). However, this feels like an argument for some syntactic sugar, like the "with" block found in some languages: with($e) { // Inside this block $a is actually compiled to mean $e->a } Not that this can be entirely de-sugared by a compiler or static analysis tool, so can be completely ignored by optimisation, and reliably processed by code inspection and refactoring aids. This isn't true of compact(), variable-variables, etc, because by exchanging strings and variable names you are writing fundamentally dynamic code. Regards, -- Rowan Collins [IMSoP]$e['d'] = $this->d(); $e['a'] = pow($e['d'], $e['d'] + 1); $e['c'] = $e['a'] ^ 0b1100; $e['b'] = $e['a'] - $e['d'];return new B($e);} That is far more cumbersome.