71 lines
1.6 KiB
Markdown
71 lines
1.6 KiB
Markdown
---
|
||
title: Variables
|
||
localeTitle: 变量
|
||
---
|
||
## 变量
|
||
|
||
# 创建(声明)PHP变量
|
||
|
||
变量是用于存储信息的“容器”。
|
||
|
||
**句法:**
|
||
|
||
```php
|
||
<?php
|
||
$txt = "Hello world!";
|
||
$x = 5;
|
||
$y = 10.5;
|
||
?>
|
||
```
|
||
|
||
在执行上述语句之后,变量$ txt将保持值Hello world!,变量$ x将保持值5,变量$ y将保持值10.5。
|
||
|
||
##### 注意:为变量指定文本值时,请在值周围加上引号。
|
||
|
||
##### 注意:与其他编程语言不同,PHP没有声明变量的命令。它是在您第一次为其赋值时创建的。
|
||
|
||
# PHP变量的规则:
|
||
|
||
* 变量以$符号开头,后跟变量名称
|
||
* 变量名必须以字母或下划线字符开头
|
||
* 变量名称不能以数字开头
|
||
* 变量名只能包含字母数字字符和下划线(Az,0-9和\_)
|
||
* 变量名称区分大小写($ age和$ AGE是两个不同的变量)
|
||
|
||
# 输出变量
|
||
|
||
PHP echo语句通常用于将数据输出到屏幕。
|
||
|
||
以下示例将说明如何输出文本和变量:
|
||
|
||
```php
|
||
<?php
|
||
$txt = "github.com";
|
||
echo "I love $txt!";
|
||
?>
|
||
```
|
||
|
||
以下示例将生成与上面示例相同的输出:
|
||
|
||
```php
|
||
<?php
|
||
$txt = "github.com";
|
||
echo "I love " . $txt . "!";
|
||
?>
|
||
```
|
||
|
||
以下示例将输出两个变量的总和:
|
||
|
||
```php
|
||
<?php
|
||
$x = 5;
|
||
$y = 4;
|
||
echo $x + $y;
|
||
?>
|
||
```
|
||
|
||
# PHP是一种松散类型的语言
|
||
|
||
在上面的例子中,请注意我们不必告诉PHP该变量是哪种数据类型。 PHP会自动将变量转换为正确的数据类型,具体取决于其值。 在其他语言(如C,C ++和Java)中,程序员必须在使用之前声明变量的名称和类型。
|
||
|
||
#### 更多信息: |