开发者

Why are there two $$ signs infront of variable? [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

what does $$ mean in PHP?

开发者_JS百科

I recently needed to make a change on a application and came across this $pageObject->createPageContent($$templateName);

The method looked like this

function createPageContent($page_content_html) {
        $this->page_content = $page_content_html;
    }

My question is when I removed the one $ sign infront of the variable I got a different result as with the double $$. Why is there one $ sign extra? What's the purpose for this?


$$ signifies a variable variable in PHP.

It's an easy way to reference an already existing variable by a string.

Here's an example:

$someVar = 'something';

$varname = 'someVar';

echo $$varname; //something

So, in your example, $templateName actually references the name of an already existing variable, so when you prepend it with another $, PHP gets the value out of that variable. This is a very powerful language feature IMHO.


$$ represents a variable variable. The result of $templateName is used as the variable name you wish to reference. For further clarity, it can also be written as

${$templateName}

For example,

$templateName = "hello";
$hello = "world";

echo $$templateName;
//-> "world"

http://php.net/manual/en/language.variables.variable.php


When you're using two $$ it means the name of the variable is actually a veriable.

$animal = "cow";

$cow = "moo";

echo $$animal;

//Prints 'moo'


This way you are able to address variables dynamically.

There is a perfect description to be found at php.net.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜