Variables for beginners to PHP

Variables in PHP are represented by a dollar sign followed by the variable name.

Variable names are case-sensitive.

Variable names follow the same rules as other tags in PHP.

A valid variable name starts with a letter or

or an underscore, followed by any number of letters, numbers, or underscores

Note: The letters mentioned here are a-z, A-Z, and ASCII characters from 127 to 255 (0x7f-0xff).

$this is a special variable that cannot be assigned a value

PHP variable naming rules

1. Variables start with the dollar sign $. Such as $name, $age.

2. The first character after the dollar sign $ cannot be a number, but can only be an underscore_ or a letter. Variables like $1_1 are wrong.

3. Except for underscore_, no spaces or punctuation marks are allowed in variables. That is to say, the variable name can only contain: a-z, A-Z, 0-9 and underscore_.

4. PHP variable names are case-sensitive. For example, $name and $Name are two different variables

<?php
	$var  =  'Bob' ;
	$Var  =  'Joe' ;
	echo  "$var,$Var";       // 输出 "Bob, Joe"

	//site   =  'not yet' ;      // 非法变量名;以数字开头
	
	$_4site   =  'not yet' ;     // 合法变量名;以下划线开头
	$i站点is  =  'mansikka' ;   // 合法变量名;可以用中文

?>

The scope of the variable:

The scope of the variable is the part of the script where the variable can be referenced/used

local       global       static   parameter

global keyword is used to access global variables within a function

<?php
	$x=5;
	$y=10;

	function myTest(){
		global $x,$y;
		$y=$x+$y;
	}

	myTest();
	echo $y; 
?>

PHP will all global Variables are stored in an array named $GLOBALS[index]. index holds the name of the variable. This array can be accessed inside the function or used directly to update global variables.

<?php

	function myTest(){
		static $x=0;
		echo $x;
		$x++;
	}

	myTest();
	myTest();
	myTest();

?>

static Static variables only exist in the local function scope, but when the program execution leaves this scope, its value is not lost

Then, each time the function is called, the variable The value from the last time the function was called will be retained.

Note: This variable is still a local variable of the function.

<?php
	$x=5;
	$y=10;

	function myTest(){
		$GLOBALS['y']=$GLOBALS['x']+$GLOBALS['y'];
	} 

	myTest();
	echo $y;

?>

Parameter scope

Parameters are local variables whose values ​​are passed to the function through the calling code.

Parameters are declared in the parameter list as part of the function declaration:

<?php

	function myTest($x){
		echo $x;
	}

	myTest(5);

?>


Continuing Learning
||
<?php $var = 'Bob' ; $Var = 'Joe' ; echo "$var,$Var"; // 输出 "Bob, Joe" $4site = 'not yet' ; // 非法变量名;以数字开头 $_4site = 'not yet' ; // 合法变量名;以下划线开头 $i站点is = 'mansikka' ; // 合法变量名;可以用中文 ?>
submitReset Code
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!