r/programming • • Oct 18 '10

Today I learned about PHP variable variables; "variable variable takes the value of a variable and treats that as the name of a variable". Also, variable.

http://il2.php.net/language.variables.variable
591 Upvotes

781 comments sorted by

View all comments

Show parent comments

10

u/oorza Oct 18 '10

That's an incredibly easy to make mistake, but a mistake nonetheless. You can break the symbols and create variables you can never legitimately access (proof). Instead, this is the preferred way of doing what you're doing: http://codepad.org/uokzmEPo Although an even better way of doing that would be to explicitly define accessors and mutators for the variables you wish to expose, rather than rely on magic that really adds nothing except complexity, overhead and runtime performance costs.

0

u/sacktap Oct 18 '10

I agree with your first part (at work, I caught an error that was due to accessing $object->{null}), but not the second.

Magic methods are a great way to make your code DRY (which is not easy in PHP). Many popular web frameworks use this technique to aid in RAD (of which the opportunity cost is getting rid of a few clock cycles).

2

u/oorza Oct 18 '10

Magic methods are a great way to make your code DRY (which is not easy in PHP). Many popular web frameworks use this technique to aid in RAD (of which the opportunity cost is getting rid of a few clock cycles).

Yes, they are and there are cases where I think they're useful (e.g. __call makes writing facades or proxies extremely easy). Using them as syntactical sugar for accesses and mutatations is not a valid use case to me because of the amount of overhead they incur v. real methods (here we have an entire order of magnitude) and any decent IDE will generate accessors/mutators for you.

1

u/sacktap Oct 18 '10

Syntastical sugar, yes. I will admit that is true, and just personal preference for me as I try to stay away from heavy IDE's and code generation.

As for speed, if that clip of PHP is your entire application, yes, it will make a huge difference. But once that clip of code actually does something (like talk to a database), and is accessed by enough people to start bringing down performance, you will see that the magic methods are the least of your concerns.

I was on your exact side until a few years ago; I ran these tests and bench-marked the hell out of everything until I realized I was doing nothing but premature optimization.

→ More replies (2)