Home  >  Article  >  Backend Development  >  Variables - PHP Manual Notes

Variables - PHP Manual Notes

WBOY
WBOYOriginal
2016-08-08 09:29:28852browse

Basics

Variables in PHP are represented by a dollar sign followed by the variable name. Variable names are case-sensitive, and Chinese characters may also be legal.

Variables are always assigned by value by default. PHP also provides another way to assign values ​​to variables: reference assignment. This means that the new variable simply references (in other words, "aliases" or "points to") the original variable. Changing the new variable will affect the original variable and vice versa. To use reference assignment, simply add an ampersand to the variable to be assigned (the source variable). Note that only named variables can be assigned by reference.

Predefined variables

PHP has a large number of predefined variables, many of which depend on the server. Some predefined variables do not take effect when run from the command line.

PHP provides an additional set of predetermined array variables that contain data from the web server (if available), the running environment, and user input. These array variables are often called autoglobals or superglobals. .

Variable scope

The variable scope here refers to the context in which it is defined, that is, its effective scope. The scope of variables includes files introduced by include and require.

PHP’s global variables are a little different from C language. In C language, global variables automatically take effect in functions unless overridden by local variables. Global variables in PHP must be declared global when used in functions.

<code><?php 
$a = &#39;hello&#39;;
function test() {
	var_dump($a);
}
// test();
include &#39;b.inc&#39;;</code>

b.incThe content is as follows:

<code><?php 
echo &#39;hello&#39;;
?></code>

The program can output hello normally, but the commented out test() cannot be parsed normally because the variable $a is undefined.

Use global variables

If you want to use global variables in a function, you can use the following two methods.

  1. global keyword
<code>global $a, $b;</code>

After you declare a global variable in a function, all references to any variable will point to its global version.

  1. $GLOBALS super global variable array
<code>$GLOBALS['b'] = $GLOBALS['a'] + $BLOBALS['b'];</code>

Usage is similar to the global keyword.

Static variables

Static variables only exist in the local function scope, but their values ​​are not lost when the program execution leaves this scope. Moreover, it is only initialized once when it is declared, and the value of the static function will not be overwritten each time the function is called.

Assigning a static variable with the result of an expression in the declaration will cause a parsing error. Static declarations are parsed at compile time.

<code><?php 
function test() {
	static $cnt = 0;
	echo $cnt;
	$cnt++;
	if($cnt < 10) {
		test();
	}
	$cnt--;
}
test();</code>

Similar to static in C language, the following C code can also output ten numbers from 0 to 9 in sequence.

<code>#include <stdio.h>
void test(void) {
	static int cnt = 0;
	printf("%d ", cnt);
	cnt++;
	if(cnt < 10) {
		test();
	}
	cnt--;
}
int main(void) {
	test();
	return 0;
}</code>

The static and global definitions of variables are implemented by reference.

Variable variables

Variable variables are a special usage in PHP language. I don’t know if they exist in other languages.

In short, a variable variable means that a variable variable obtains the value of an ordinary variable as the variable name of the variable variable.

<code><?php 
$a = &#39;hello&#39;;
$$a = &#39;world&#39;;
echo "$a $$a";  // hello $hello
echo "$a ${$a}";  // hello world</code>

When mutable variables are used in arrays, ambiguities may arise. For example, if you write $$a[1], the compiler will report an error. The meaning you want to express needs to be replaced by the following two methods.

${$a[1]}
$a[1] as a variable

${$a}[1]
$$a as a variable and take out the value with index 1 in the variable.

Form variables

When a form is submitted to a PHP script, the information in the form is automatically available in the script and can be accessed via $_GET[], $_POST[] and $_REQUEST[].

Note that dots and spaces in variable names are converted to underscores. For example, <input name="a.b"> becomes $_REQUEST["a_b"]. The following example shows the use of identifiers in the form.

<code><form action="process.php" method="post">
<input name="my.text" type="text">
<input name="my text" type="text">
<input name="my_text" type="text">
<input type="submit">
</form></code>

Form processing file process.php.

<code><?php 
var_dump(isset($_POST[&#39;my.text&#39;]));
var_dump(isset($_POST[&#39;mytext&#39;]));
var_dump(isset($_POST[&#39;my_text&#39;]));
var_dump($_POST[&#39;my_text&#39;]);</code>

Because the period is not a legal character in PHP variable names, the output is as follows.

<code>boolean false

boolean false

boolean true

string &#39;h3&#39; (length=2)</code>

magic_quotes_gpcThe configuration directive affects the value of get/post/cooie. This feature has been deprecated and removed. Single quotes, double quotes, backslashes and NULL characters in the input will not be escaped. If you need to escape, you can use addslashes(). If you need to dequote a quoted string, you need to use stripslashes().

PHP also understands arrays in the context of form variables. The example below uses a more complex form variable and posts the form to itself and displays the data on submission.

<code><?php 
if(isset($_POST[&#39;action&#39;])) {
	var_dump($_POST);
} else {
	$page = $_SERVER[&#39;PHP_SELF&#39;];
	$s = <<<STR
<form action="{$_SERVER[&#39;PHP_SELF&#39;]}" method="post">
<input type="text" name="personal[name]">
<input type="text" name="personal[detail]">
<select multiple name="option[]">
	<option value="a">a</option>
	<option value="b">b</option>
	<option value="c">c</option>
</select>
<input type="hidden" name="action" value="submitted">
<input type="submit" name="submit">
</form>
STR;
	echo $s;
}</code>

Be extra careful when containing complex variables in the heredoc. The above code $_SERVER['PHP_SELF']without curly brackets will cause an error when running.

<code>array (size=4)
  'personal' => 
    array (size=2)
      'name' => string 'hello' (length=5)
      'detail' => string 'world' (length=5)
  'option' => 
    array (size=2)
      0 => string 'a' (length=1)
      1 => string 'c' (length=1)
  'action' => string 'submitted' (length=9)
  'submit' => string '提交查询内容' (length=12)</code>

IMAGESubmit

When submitting a form, you can use an image instead of the standard submit button. The first time I used it, it was really magical.

<code><?php 
if(isset($_POST[&#39;action&#39;])) {
	var_dump($_POST);
} else {
	$s = <<<STR
<form action="{$_SERVER[&#39;PHP_SELF&#39;]}" method="post">
<input type="hidden" name="action" value="1">
<input type="image" src="go.jpg" name="sub">
</form>
STR;
	echo $s;
}</code>

For the above program, when the user clicks somewhere in the image, the form will be sent to the server, and two variables sub_x and sub_y will be added, which contain the coordinates of the image the user clicked.

<code>array (size=3)
  'action' => string '1' (length=1)
  'sub_x' => string '334' (length=3)
  'sub_y' => string '282' (length=3)</code>

cookies

PHP can set cookies using the setcookie() function. Cookies are part of the HTTP header and therefore must be called before sending any output to the browser.

The relevant use of cookies is as follows.

<code><?php 
if(isset($_COOKIE['cnt'])) {
	$cnt = $_COOKIE['cnt'] + 1;	
	echo $cnt;
} else {
	$cnt = 1;
}
setcookie('cnt', $cnt, time() + 3600);</code>

cookie数据在相应的cookie数组中可用,如果将多个值赋给一个cookie变量,必须将其赋成数组。

(全文完)

以上就介绍了变量 - PHP手册笔记,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn