SoFunction
Updated on 2025-03-02

PHP variable variable learning summary

The so-called mutable variable means that the variable name of a variable can be dynamically set and used. Syntax forms are special syntax of PHP, which are rare in other languages.

Sometimes it is very convenient to use mutable variable names. That is to say, the variable name of a variable can be dynamically set and used. A normal variable is set by declaration, for example:

<?php
$a = 'hello';
?>

A mutable variable takes the value of a normal variable as the variable name of the mutable variable. In the above example, hello uses two dollar signs ($), and can be used as a variable variable. For example:

<?php
$$a = 'world';
?>

At this time, both variables are defined: the content of $a is "hello" and the content of $hello is "world". Therefore, the following statement:

<?php
echo "$a ${$a}";
?>

The exact same result as the following statement outputs:

<?php
echo "$a $hello";
?>

They all output: hello world.

To use mutable variables for arrays, an ambiguous problem must be solved. This is when writing $$a[1], the parser needs to know whether he wants $a[1] as a variable, or wants $$a as a variable and take out the value indexed as [1] in that variable. The syntax to solve this problem is to use ${$a[1]} for the first case and ${$a}[1] for the second case.

The attributes of a class can also be accessed through mutable attribute names. The variable attribute name will be parsed within the scope in which the call is located. For example, for the $foo->$bar expression, $bar is parsed in the local scope and its value will be used for the attribute name of $foo. The same is true for $bar when it is an array unit.

Braces can also be used to clearly define the attribute names. The most useful thing is when the attribute is in an array, or the attribute name contains multiple parts or the attribute name contains illegal characters (for example from json_decode() or SimpleXML).

Example #1 Variable Attribute Example

<?php
class foo {
  var $bar = 'I am bar.';
  var $arr = array('I am A.', 'I am B.', 'I am C.');
  var $r  = 'I am r.';
}
$foo = new foo();
$bar = 'bar';
$baz = array('foo', 'bar', 'baz', 'quux');
echo $foo->$bar . "\n";
echo $foo->$baz[1] . "\n";
$start = 'b';
$end  = 'ar';
echo $foo->{$start . $end} . "\n";
$arr = 'arr';
echo $foo->$arr[1] . "\n";
echo $foo->{$arr}[1] . "\n";
?>

The above routine will output:

I am bar.
I am bar.
I am bar.
I am r.
I am B.

Example #2 Variable Attribute Example

<?php
 //You can even add more Dollar Signs
 $Bar = "a";
 $Foo = "Bar";
 $World = "Foo";
 $Hello = "World";
 $a = "Hello";
 $a; //Returns Hello
 $$a; //Returns World
 $$$a; //Returns Foo
 $$$$a; //Returns Bar
 $$$$$a; //Returns a
 $$$$$$a; //Returns Hello
 $$$$$$$a; //Returns World
 //... and so on ...//
?>

Example #3 Variable Attribute Example

<?php
// Given these variables ...
$nameTypes  = array("first", "last", "company");
$name_first  = "John";
$name_last  = "Doe";
$name_company = "";
// Then this loop is ...
foreach($nameTypes as $type)
 print ${"name_$type"} . "\n";
// ... equivalent to this print statement.
print "$name_first\n$name_last\n$name_company\n";
?>

The above routine will output:

John
Doe

John
Doe

ps: Detailed introduction to PHP variable parameters

This article is mainly aimed at the beginners of PHP learning, so we will use a specific example to explain it.

First, we need to write a PHP function to calculate the sum of two numbers, which can be written as follows:

/**
  * Calculate the sum of two numbers and return the calculated result
  * @param number $a
  * @param number $b
  * @return number
  */
function sum($a, $b){
  return $a + $b;
}

Similarly, if we need to calculate the sum of three numbers, we can write as follows:

/**
  * Calculate the sum of two or three numbers and return the calculated result
  * @param number $a
  * @param number $b
  * @return number $c This parameter can not be passed in value, default is 0
  */
function sum($a, $b, $c = 0){
  return $a + $b + $c;
}

At this point, if we need to calculate the sum of any number, how do we need to write PHP functions?

Of course, you might consider using arrays as passing parameters to implement such functions:

/**
  * Calculate the sum of any number, the function parameter params must be of array type
  * @param array params
  */
function sum($params){
  $total = 0;
  foreach ($params as $i){
    $total += $i;
  }
  return $total;
}

Well, this approach is indeed not wrong, because in the process of program development before the birth of variable parameters, whenever there is a need to pass any multiple parameters, they are represented by arrays or other similar sets. However, does this transmission seem to be not clear and intuitive enough? As a PHP programmer, you should know that in PHP there is a function var_dump() for displaying variable details, for example:

$age = 18;
var_dump($age); //Display variables$ageDetails of

When you need to display information about multiple variables, we can also use it like this:

$name = 'Zhang San';
$age = 18;
$gender = true;
var_dump($name, $age, $gender);

We know that var_dump() can receive as many variables at the same time and does not need to be passed in the form of an array. This parameter transfer method seems more intuitive and elegant. This form of passing any multiple parameters is called a variable parameter. Of course, our sum() function can also be implemented in this way:

/**
  * Calculate the sum of any number and return the calculated result
  */
function sum(){ //There is no parameter defined in the brackets here  $total = 0;
  //Use func_get_args() to get all the actual passed parameters of the current function, and the return value is array type  $varArray = func_get_args();
  foreach ($varArray as $var){
    $total += $var;
  }
  return $total;
}
/***The following is a call example****/
echo sum(1, 3, 5); //Calculate 1+3+5echo sum(1, 2); //Calculate 1+2echo sum(1, 2, 3, 4);  //calculate1+2+3+4

As shown in the above example, as long as you use the PHP built-in function func_get_args() in the current function, you can call the actual parameter array when the function is called, and then we only need to process the parameter array.

Note 1:1. If no parameters are passed in when calling, the function func_get_args() returns the array type, but is just an empty array (the array does not contain any elements). 2.func_get_args() can only be called in the function, otherwise a warning message will be displayed. 3. The func_get_args() function can receive an index parameter to obtain the parameters at the specified index in the parameter array. For example, if you want to get the first parameter passed in, you can call: func_get_args(1) like this.

4. In addition, you can also call func_num_args() in the function, which can return the number of parameters passed in the current function call.

Note 2: The implementation of PHP mutable parameters is very similar to that of JavaScript mutable parameters. PHP uses the built-in function func_get_args() to implement it, and JavaScript uses the built-in variable arguments to implement it.

Note 3:In the last sum() function code, the sum() function does not define any formal parameters, so when calling the function, you can pass in 0, 1, 2~n parameters. However, in general, the calculation sum needs at least two numbers to participate in the calculation. Therefore, you can define two formal parameters at the definition of the sum() function, such as: sum($a, $b), and other codes remain unchanged. In this way, at least two parameters must be passed in when the function is called.

Note 4:Since PHP already has built-in function array_sum() to calculate the sum of all elements in an array, the final version of the above code is as follows:

/**
  * Calculate the sum of any number and return the calculated result
  */
function sum($a, $b){
  return array_sum(func_get_args());
}