php中的变量是保存数据的内存位置的名称。 变量是用于保存临时数据的临时存储。
在php中,使用$
符号和变量名来声明变量。
在php中声明变量的语法如下:
$variablename = value;
下面来看看看如何在php变量中声明字符串,整数和浮点值的例子。
file: variable1.php
<?php
$str="hello string";
$x=200;
$y=44.6;
echo "string is: $str <br/>";
echo "integer is: $x <br/>";
echo "float is: $y <br/>";
?>
执行上面代码得到以下结果-
string is: hello string
integer is: 200
float is: 44.6
file: variable2.php
<?php
$x=5;
$y=6;
$z=$x+$y;
echo $z;
?>
执行上面代码得到以下结果-
11
在php中,变量名称是区分大小写的。 因此,变量名称“color
”不同于”color
“,”color
“等。
file: variable3.php
<?php
$color="red";
echo "my car is " . $color . "<br>";
echo "my house is " . $color . "<br>";
echo "my boat is " . $color . "<br>";
?>
执行上面代码得到以下结果-
my car is red
notice: undefined variable: color in c:\wamp\www\variable.php on line 4
my house is
notice: undefined variable: color in c:\wamp\www\variable.php on line 5
my boat is
php变量必须以字母或下划线开头。php变量不能以数字和特殊符号开头。
file: variablevalid.php
<?php
$a="hello";//letter (valid)
$_b="hello";//underscore (valid)
echo "$a <br/> $_b";
?>
执行上面代码得到以下结果 -
hello
hello
file: variableinvalid.php
<?php
$4c="hello";//number (invalid)
$*d="hello";//special symbol (invalid)
echo "$4c <br/> $*d";
?>
执行上面代码得到以下结果 -
parse error: syntax error, unexpected '4' (t_lnumber), expecting variable (t_variable)
or '$' in c:\wamp\www\variableinvalid.php on line 2
php是一种宽松类型的语言,因此,php自动将变量转换为正确的数据类型。