0

How does PHP handle something like this:

$blah = "Testing a variable"; 
$$blah = "test"; 

What would I access my dynamically declared variable?

6
  • mmk k, so something like.. $blah = str_replace(" ", "_", $blah); would work sufficiently. Commented Dec 22, 2010 at 17:41
  • 1
    $$ is one of the true evils/joys of PHP. combine with () for fun-ness! $$blah()(); Commented Dec 22, 2010 at 17:42
  • ${"Testing a variable"} works fine. Commented Dec 22, 2010 at 17:45
  • 1
    @DampeS8N in what universe is this a joy? Commented Dec 22, 2010 at 18:16
  • 1
    The one where you are coding for fun on your own? It is like coding in brainfuck. Joy. Commented Dec 22, 2010 at 18:18

4 Answers 4

9

Everything you need to know about variable variables at http://www.php.net/manual/en/language.variables.variable.php, except for one thing: don't use them.

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

2 Comments

-1 for giving me a link to the manual, +1 for giving me some useful syntax advice.
@Stephen I know, right? The manual explains variable variables way better than most people here could.
4

echo ${'Testing a variable'};

However, you don't want to do this in practice. It makes for unmaintainable, bug-prone code.

Comments

1

The variable $blah must contain a valid variable name.

This will tell you about variables: http://www.php.net/manual/en/language.variables.basics.php

Comments

0

Not really an answer, but...

<?php 
function I_love_you()
{
    return "haha";
}

$haha = "HoHoHo";
$tom = "I_love_you";
$blah = "tom";

echo ${$$blah()};
?>

Comments

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.