PHP variable Variable Learning summary _php example

Source: Internet
Author: User

Variable variables, the variable names of a variable can be dynamically set and used. Syntax form is a special syntax for PHP, which is rare in other languages.

Sometimes it is convenient to use variable variable names. That is, the variable name of a variable can be set and used dynamically. An ordinary variable is set by a declaration, for example:

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

A variable variable obtains the value of a normal variable as the variable name of this variable variable. In the example above, Hello uses the two dollar sign ($), which can be used as a variable variable. For example:

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

At this point, two variables are defined: The $a content is "hello" and $hello content is "world". Therefore, the following statement:

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

Output exactly the same result as the following statement:

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

They all output: Hello world.

To use variable variables with arrays, you must resolve an ambiguous problem. This is when you write $ $a [1], the parser needs to know if you want to $a [1] as a variable, or if you want $ $a as a variable and take out the value indexed by [1] in the variable. The syntax for solving this problem is to use the ${$a [1]} for the first case, with ${$a}[1] for the second case.

The properties of a class can also be accessed through a mutable property name. The variable attribute name is resolved within the scope of the call. For example, for $foo-> $bar expression, the $bar is parsed locally and its value is used for the property name of the $foo. The same is true for $bar are array cells.

You can also use curly braces to give the property name a clear delimitation. The most useful is when the attribute is in an array, or the property name contains more than one part or the property name contains an illegal character characters (for example, from Json_decode () or SimpleXML).

Example #1 Variable Properties sample

<?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 routines will output:

I am Bar.
I am Bar.
I am Bar.
I am R.
I am B.

Example #2 Variable Properties sample

<?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 Properties sample

<?php
//Given These variables ...
$nameTypes  = Array ("A", "last", "Company");
$name _first  = "John";
$name _last  = "Doe";
$name _company = "Php.net";
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 routines will output:

John
Doe
Php.net
John
Doe
Php.net

Introduction to ps:php variable parameters

This article is mainly for beginners in PHP learning, so we use a specific example to explain.

First, we need to write a PHP function to compute the two-digit and, you can write as follows:

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

Similarly, if we need to compute the number of three digits, we can write as follows:

/**
 * Calculates the number of two or three numbers and returns the result of the calculation
 * $a
 * @param number $b *
 @return number $c The parameter may not pass in the value, the default is 0 c14/>*/
function sum ($a, $b, $c = 0) {return
  $a + $b + $c;
}

At this point, if we need to compute as many numbers as we want, how do we write PHP functions?

Of course, you might consider using an array as the pass parameter of a function to implement this function:

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

Well, there's nothing wrong with that, because in the development of a program prior to the birth of a variable parameter, it is represented by an array or other similar collection when you encounter any number of arguments that need to be passed. However, is this transmission not clear and intuitive? As a PHP programmer, you should know that there is a function var_dump () for displaying variable details in PHP, for example:

$age =;
Var_dump ($age); Show details of variable $age

When you need to display information for multiple variables, we can also use this:

$name = ' John ';
$age =;
$gender = true;
Var_dump ($name, $age, $gender);

We know that Var_dump () can receive any number of variables at the same time, and do not need to be in the form of an array of transmission, so that the parameters of the transmission method is more intuitive and elegant. This form of passing any number of arguments is called a variable parameter. Of course, our sum () function can also be implemented in this way:

/**
 * Computes any number of sums and returns the result of the calculation *
/function sum () {//The parentheses here do not define any parameters
  $total = 0;
  Use Func_get_args () to get all the actual pass parameters of the current function, with the return value of array type
  $varArray = Func_get_args ();
  foreach ($varArray as $var) {
    $total + = $var;
  }
  return $total;
}
/***** The following is the invocation example *****/
echo sum (1, 3, 5);//COMPUTE 1+3+5
echo sum (1, 2);//COMPUTE 1+2
echo sum (1, 2, 3, 4);  Calculate 1+2+3+4

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

Note 1: 1. If no arguments are passed in when invoked, the function Func_get_args () returns the array type, but is an empty array (the array contains no elements). 2.func_get_args () can only be called in a function, or a warning message is displayed. The 3.func_get_args () function can receive an index parameter that gets the arguments at the specified index in the parameter array. For example, if you want to get the first argument passed in, you can call this: Func_get_args (1).

4. In addition, you can call Func_num_args () in a function to return the number of arguments passed in by the current function call.

Note 2: PHP's variable parameters are implemented in much the same way that JavaScript variable parameters are implemented, PHP uses built-in function Func_get_args (), and JavaScript is implemented using the built-in variable arguments of the function.

Note 3: in the final sum () function code, the sum () function does not define any form parameters, so it can be passed in 0, 1, and 2~n arguments when calling the function. In general, however, calculations and a minimum of two digits are required to participate in the calculation. Therefore, you can define two formal parameters, such as sum ($a, $b) at the definition of the sum () function, and the other code remains unchanged. This way, when you call the function, you must pass in at least two parameters.

Note 4: since PHP has built-in function array_sum () to compute the and of all elements in the array, the final version of the above code is as follows:

/**
 * Computes any number of sums and returns the computed result/
function sum ($a, $b) {return array_sum (
  Func_get_args ());
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.