PHP variable Learning Summary

Source: Internet
Author: User
A variable is a variable whose name can be dynamically set and used. The syntax form is a special syntax of PHP, which is rare in other languages. This article will share with you a summary of php variable learning. if you are interested in php variable-related knowledge, let's learn the so-called variable, the variable name can be dynamically set and used. The syntax format is a special syntax of PHP, which is rare in other languages.

Sometimes it is convenient to use a variable name. That is to say, the variable name of a variable can be dynamically set and used. A common variable is set through declaration, for example:

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

A variable obtains the value of a common variable as the variable name of the variable. In the preceding example, after using two dollar signs ($), hello can be used as a variable of variable. For example:

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

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

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

The output result is exactly the same as that of the following statement:

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

They all output: hello world.

To use variables in an array, you must solve an ambiguous problem. When writing $ a [1], the parser needs to know that $ a [1] is used as a variable, you still want $ a as a variable and retrieve the value of [1] in the variable. The syntax for solving this problem is to use $ {$ a [1]} for the first case and $ {$ a} [1] for the second case.

Class attributes can also be accessed through variable attribute names. Variable attributes will be parsed within the scope of the call. For example, for the $ foo-> $ bar expression, $ bar is parsed in the local range and its value is used for the attribute name of $ foo. The same applies when $ bar is an array unit.

You can also use curly brackets to clearly define attribute names. It is most useful when an attribute is located in an array, or when the attribute name package contains multiple parts or the attribute name package contains invalid characters (for example, from json_decode () or SimpleXML ).

Example #1 variable attributes

<?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";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 examples of variable attributes

<?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 attributes

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

John
Doe
PHP.net
John
Doe
PHP.net

Ps: PHP variable parameters

This article is mainly intended for PHP beginners. Therefore, we will give a specific example to introduce 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 calculation result * @ param number $ a * @ param number $ B * @ return number */function sum ($, $ B) {return $ a + $ B ;}

Similarly, if we need to calculate the sum of three numbers, we can write it 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 be left blank, the default value is 0 */function sum ($ a, $ B, $ c = 0) {return $ a + $ B + $ c ;}

Now, if we need to calculate any number of sums, how do we compile PHP functions?

Of course, you may consider using arrays as the parameter passed by the function to implement this function:

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

Well, this is indeed correct, because in the process of program development before the birth of variable parameters, when you need to pass any number of parameters, are represented by arrays or other similar sets. However, isn't the transfer clear and intuitive? As a PHP programmer, you should know that there is a function var_dump () in PHP that is used to display variable details. for example:

$ Age = 18; var_dump ($ age); // display the details of the variable $ age

When you need to display the information of multiple variables, you can also use the following:

$ Name = 'Zhang San'; $ age = 18; $ 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. this parameter transmission method is more intuitive and elegant. This form of passing any number of parameters is called variable parameters. Of course, our sum () function can also be implemented in this way:

/*** Calculate any number of sums and return the calculated result */function sum () {// no parameter is defined in the brackets here $ total = 0; // use func_get_args () to obtain all the actual passing parameters of the current function. the returned 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 + 5 echo sum (1, 2); // calculate 1 + 2 echo sum (1, 2, 3, 4 ); // calculate 1 + 2 + 3 + 4

As shown in the preceding example, you can use the PHP built-in function func_get_args () in the current function to call the actual parameter array passed by the function. then, you only need to process the parameter array.

Note 1:1. If no parameter is input during the call, the function func_get_args () returns an array type, but an empty array (the array does not contain any element ). 2. func_get_args () can only be called in the function; otherwise, a warning message is displayed. 3. the func_get_args () function can receive an index parameter, which is used to obtain the parameter at the specified index in the parameter array. For example, to obtain the first passed parameter, you can call func_get_args (1 ).

4. you can also call func_num_args () in the function to return the number of parameters passed in by the current function call.

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

Note 3:In the final sum () function code, the sum () function does not define any form parameter, so when calling this function, you can input 0, 1, 2 ~ N parameters. However, in general, the calculation requires at least two numbers. Therefore, you can define two formal parameters in the definition of the sum () function, for example, sum ($ a, $ B). other code remains unchanged. In this way, at least two parameters must be input when the function is called.

Note 4:Since PHP has built in the array_sum () function for calculating the sum of all elements in the array, the final version of the above code is as follows:

/*** Calculate any number of sums and return the calculated 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.