PHP variable variables

Variable variables

That is where Variable name is determined by a Variable, in simple words A variable variable takes the value of a variable and treats that as the name of a variable.

Example 1:

$a = 'hello';
$hello = 'world';

echo "$a ${$a}";
echo"<br />";
echo $a . ' ' . $$a;
echo"<br />";
echo "$a $hello";
echo"<br />";

Output 1:

hello world
hello world
hello world

Example 2:

$bar = "a";
$foo = "bar";
$world = "foo";
$hello = "world";
$a = "hello";

echo $a; //Returns hello
echo"<br />";
echo $$a; //Returns world
echo"<br />";
echo $$$a; //Returns foo
echo"<br />";
echo $$$$a; //Returns bar
echo"<br />";
echo $$$$$a; //Returns a
echo"<br />";

echo $$$$$$a; //Returns hello
echo"<br />";
echo $$$$$$$a; //Returns world
echo"<br />";

Example 3:

class Customer {

  public $firstname;
  public $lastname;
  public $country;
  public $gender;

  public function create() {
    echo "Output: <br />";
    echo $this->firstname . ' ' . $this->lastname;
    echo "<br />";
    echo $this->gender;
    echo "<br />";
    echo $this->country;
  }

}

$arr = array('firstname' => 'Samit',
  'lastname' => 'Khulve',
  'gender' => 'Male',
  'country' => 'India');

usually in my action script many developerd would map these array fields into class variables one by one as follows:

$customer = new Customer();
$customer->firstname = $_POST['firstname'];
$customer->lastname = $_POST['lastname'];
$customer->country = $_POST['country'];
$customer->gender = $_POST['gender'];

$customer->create();

But using variable variables We can easily map all associative array values into class variables using the following one line foreach loop;

$customer = new Customer();
foreach ($arr as $key => $val) {
  $customer->$key = $val;
  // OR we can use {}
  // $customer->{$key} = $val;
}

$customer->create();

Output 3:

Output:
Samit Khulve
Male
India

 

Tags