Use indirect variable reference in PHP

Description

The following code shows how to use indirect variable reference.

Example


/*from   w w  w.ja  va  2  s . c  o m*/
<?php
  //set variables
  $var_name = "myValue";
  $myValue = 123.456;
  $array_name = "myArray";
  $myArray = array(1, 2, 3);

  //prints "123.456"
  print($$var_name . "<br>\n");

  //prints "$myValue"
  //$var_name expands to "myValue", but indirect
  //reference doesn't work inside quoted strings,
  //and the extra dollar sign is printed as-is
  print("$$var_name<br>\n");

  //prints "123.456"
  //Uses special notation to embed complex variables
  //inside strings
  print("{$$var_name}<br>\n");

  //prints "3"
  print(${$array_name}[2] . "<br>\n");
?>

The code above generates the following result.





















Home »
  PHP Tutorial »
    Language Basic »




PHP Introduction
PHP Operators
PHP Statements
Variable
PHP Function Create
Exception
PHP Class Definition