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

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

5

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

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

Outputs 1

6 Comments

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 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.
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 You are probably right, it seems the only time they come up is when people want to know what they do...
@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.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.