阅读(4851) (0)

PHP简介

2017-02-22 16:40:20 更新

PHP教程 - PHP简介

PHP脚本通常以文件扩展名 .php 保存。

声明

PHP代码的基本单位称为语句,以分号结尾。

通常一行代码只包含一个语句,但我们可以有许多语句在一行上你想要的。

PHP打开和关闭代码岛

<?php ?> 标记了PHP代码岛。

短标签版本是<??>

<?="Hello, world!" ?>

这里是等价的,使用标准的打开和关闭标签:

<?php 
   print "Hello, world!";
?>


示例 - PHP语句

以下PHP代码使用print语句输出消息到屏幕上。

<?php
        // option 1
        print "Hello, ";
        print "world!";

        // option 2
        print "Hello, "; print "world!";
?>

上面的代码生成以下结果。

echo 是另一个我们可以用来输出消息的命令。 echo 更有用,因为你可以传递它几个参数,像这样:

<?php
        echo "This ", "is ", "a ", "test.";
?>

上面的代码生成以下结果。

要使用打印执行相同操作,您需要使用连接操作(。)将字符串连接在一起。



PHP变量

变量是持有某个值的容器。

句法

PHP中的变量以 $ 开头,后跟字母或下划线,然后是字母,数字和下划线字符的任意组合。

这里是我们将遵循的命名变量的规则。

  • Variable names begin with a dollar sign ( $ )
  • The first character after the dollar sign must be a letter or an underscore
  • The remaining characters in the name may be letters, numbers, or underscores without a fixed limit

示例 - 定义PHP变量

我们不能使用数字启动变量。下表中显示了有效和无效变量名称的列表。

变量 描述
$myvar Correct
$Name Correct
$_Age Correct
$___AGE___ Correct
$Name91 Correct;
$1Name 不正确; 以数字开头
$Name"s 不正确; 不允许使用除“_"以外的符号

变量区分大小写。 $ Foo $ foo 不是同一个变量。

变量替换

在PHP中,我们可以将变量名写入一个长字符串,PHP知道如何用其值替换变量。这里是一个脚本显示分配和输出数据。

<?php
       $name = "www.zijiebao.com";
       print "Your name is $name\n";
       $name2 = $name;
       print "Goodbye, $name2!\n";
?>

上面的代码生成以下结果。

PHP不会在单引号字符串中执行变量替换,并赢得了“t取代大多数转义字符。

在下面的例子中,我们可以看到:

  • In double-quoted strings, PHP will replace $name with its value;
  • In a single-quoted string, PHP will output the text $name just like that.
<?php
        $food = "grapefruit";
        print "These ${food}s aren"t ripe yet.";
        print "These {$food}s aren"t ripe yet.";
?>

上面的代码生成以下结果。

大括号{}告诉变量结束的位置。