Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In PHP, are there other uses for $? Why isn't this code producing an error?

Tags:

php

In PHP, the following code will not produce a syntax error. As a developer, this will produce a syntax error in my head. Any clue?

<?php
$ $ $ $ $ $ $what_the_hell_php = 'what is wrong with you PHP?';

echo $what_the_hell_php; // no output
echo $ $ $ $ $ $ $what_the_hell_php; // worth a try but no output too

// echo $; // well, don't do this. this produces an actual PHP syntax error.

$dollars = 'a lot of money will make me crazy';
echo $dollars;
echo $$$$$$$$$$$$$$$$$$$$$$$$$$ $lotsofmoney = " - and PHP too!";

// echo $$$$$$something $hello = 'hello'; // won't work, PHP likes pure dollars

// is it for this??
echo 

   $$$     $$$$$$   $$$$$$  $$$$ $$$$       $$$    $$$$$$$$  $$$$$$$$
  $$ $$   $$    $$ $$    $$  $$   $$       $$ $$   $$     $$    $$
 $$   $$  $$       $$        $$   $$      $$   $$  $$     $$    $$
$$     $$  $$$$$$  $$        $$   $$     $$     $$ $$$$$$$$     $$
$$$$$$$$$       $$ $$        $$   $$     $$$$$$$$$ $$   $$      $$
$$     $$ $$    $$ $$    $$  $$   $$     $$     $$ $$    $$     $$
$$     $$  $$$$$$   $$$$$$  $$$$ $$$$    $$     $$ $$     $$    $$

$ascii = "<hr />\nMy ASCII art is not a string or a comment! First time!";

?>

... and the output:

a lot of money will make me crazy - and PHP too!<hr />
My ASCII art is not a text or a comment! First time!
like image 885
rationalboss Avatar asked Jul 26 '14 18:07

rationalboss


1 Answers

PHP has a concept of "variable variables" which allows you to dynamically refer to a variable by it's name. For example:

$a = 'foo';
$b = 'a';
$c = 'b';
$d = 'c';

echo $ $ $ $d; // foo

And when you're using that in an assignment? Hopefully this will help to demonstrate a bit:

$a = 'foo';
$$a = 'bar';

echo $foo; // bar

So in this code:

echo $ $ $ $ $ $ $what_the_hell_php = 'what is wrong with you PHP?'

To assign the value, the engine will get the value currently stored in $what_the_hell_php, then get the value stored in the variable with that name, then get the value stored in the variable with that name, and so on. Of course, in your example, $what_the_hell_php is initially null, so it won't actually be able to dereference these variables. However, the result of the assignment expression is still a value, just like all assignment expressions:

echo $a = $b = $c = 'foo'; // foo
like image 188
p.s.w.g Avatar answered Nov 03 '22 09:11

p.s.w.g