8

What the heck is $function(); and $$variable for?

Have never heard of these before, and searching on google doesn't give anything useful (possible that my keywords aren't perfect).

via https://stackoverflow.com/questions/4891301/top-bad-practices-in-php/4891422#4891422

Community
  • 1
  • 1
tomsseisums
  • 13,168
  • 19
  • 83
  • 145

2 Answers2

13

$function() is a variable function and $$variable is a variable variable.

Those linked pages should give you plenty to go on, or at the very least some actual words to search with.

salathe
  • 51,324
  • 12
  • 104
  • 132
5

$$variable can be quite useful. What it does:

$a = 1;
$b = "a";
echo $$b;

Outputs 1

jeroen
  • 91,079
  • 21
  • 114
  • 132
  • 4
    I've never seen a use for `$$` that wasn't an outright abuse. Variable functions, ok. But straight variable variables (with double `$$`), never. Please prove me wrong with how *useful* they can be in good code... – ircmaxell Feb 03 '11 at 21:28
  • @ircmaxell I wanted to add an example, but I can´t seem to think of any :-) Where I have used a similar construction was when generating a new object where the type / class depended on a variable (all sub-classes of a main class), something like `$product = new $type($some_var)` where `$type` is the kind of product I wanted to create. I guess that´s similar. – jeroen Feb 03 '11 at 21:39
  • It's similar and acceptable to do that. But I've just never see `$$` where it's not an example of what to do. I'd love to be proven wrong, but we'll see... – ircmaxell Feb 03 '11 at 21:42
  • @ircmaxell You are probably right, it seems the only time they come up is when people want to know what they do... – jeroen Feb 03 '11 at 21:49
  • @ircmaxell A little more similar than `new $class` would be variable class params: `return $this->$value`. Not a method, mind you, but a parameter. This is a variable variable of sorts, but still not technically `$$`. – Stephen Feb 03 '11 at 22:23
  • 1
    @ircmaxell - that's a bit like saying arrays are not needed. why use $mydata["price"] and my $data["name"] when we can use $mydata_price and $mydata_name, or (another example) why use $filename[1] and $filename[2], when $filename_1 and $filename_2 works just as easily. in other words, indirection is one of the most basic principles in a programming language. it gives you the ability to do something with a value with caring what that value is for. – unsynchronized Sep 15 '12 at 10:32