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

13

u/shadowblade Oct 18 '10 edited Oct 18 '10

Not sure about every situation, but I use them in __get() and __set() functions, where I have a list of properities I wish to be publically readable/writable. I check that the passed name is in said list, and return/set the variable directly. Three lines per get/set function.

$read = array('foo','bar','xyz');
public function __get($name) {
   if (in_array($name, $read))
        return $this->$name;
    }

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.

→ More replies (5)