Examples of mutable variables in PHP

Source: Internet
Author: User
Variable variable, variable name of a variable can be set and used dynamically. Grammar form is the special syntax of PHP, other languages are rare, this article to share PHP variable learning Summary, the knowledge of PHP variables interested in learning with friends

A variable variable name can be dynamically set and used. syntax 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 mutable variable gets the value of an ordinary variable as the variable name of the variable variable. In the example above, hello uses two dollar sign ($) and can be used as a variable variable. For example:

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

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

<?phpecho "$a ${$a}";? >

Output the exact same result as the following statement:

<?phpecho "$a $hello";? >

They all output: Hello world.

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

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

You can also use curly braces to clear the bounds of a property name. Most useful is if the property is in an array, or if the property name contains more than one part or if the property name contains an illegal character (for example, from Json_decode () or SimpleXML).

Example #1 Variable Attribute example

<?phpclass 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"; $baz echo $foo, [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 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//... on ...//?>

Example #3 Variable Attribute example

<?php//Given These variables ... $nameTypes  = Array ("First", "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:

JohnDoePHP.netJohnDoePHP.net

First, we need to write a PHP function to calculate the two number of the and can be written 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 calculate the three number of the and, can be written as follows:

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

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

Of course, you might consider the use of arrays as a function of passing parameters to implement such a function:

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

Well, there is no mistake in doing this, because in the process of developing a variable parameter before it is created, it is represented by arrays or other similar collections when it encounters the need to pass any number of arguments. However, is such a transfer not clear and intuitive? As a PHP programmer, you should know that there is a function var_dump () in PHP that displays the details of the variable, for example:

$age = 18;var_dump ($age); Show details of variable $age

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

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

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

/** * Computes any number of sums and returns the computed result */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, the return value is array type  $varArray = Func_get_args ();  foreach ($varArray as $var) {    $total + = $var;  }  return $total;} /***** Below is the invocation example *****/echo sum (1, 3, 5); Calculates 1+3+5echo sum (1, 2); Calculates 1+2echo sum (1, 2, 3, 4);  Calculate 1+2+3+4

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

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

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

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

Note 3: in the last sum () function code, the sum () function does not define any formal parameters, so it can be passed 0, 1, 2~n parameters when calling the function. However, in general, calculations and a minimum of two numbers are required to participate in the calculation. Therefore, you can define two formal parameters at the definition of the sum () function, for example: sum ($a, $b), and the rest of the code remains the same. This way, when the function is called, at least two parameters must be passed in.

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

/** * Calculates 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.