PHP 脚本可放置于文档中的任何位置。php
PHP 脚本以 <?php 开头,以 ?> 结尾:html
<?php // 此处是 PHP 代码 ?>
PHP 文件的默认文件扩展名是 ".php"。python
PHP 文件一般包含 HTML 标签以及一些 PHP 脚本代码。laravel
PHP 也容许使用短标记 <? 和 ?>,但不鼓励使用。git
只有经过激活 php.ini 中的 short_open_tag 配置指令或者在编译 PHP 时使用了配置选项 --enable-short-tags 时才能使用短标记。面试
自 PHP 5.4 起,短格式的 echo 标记 <?= 总会被识别而且合法,而无论 short_open_tag 的设置是什么。redis
若是文件内容是纯 PHP 代码,最好在文件末尾删除 PHP 结束标记。这能够避免在 PHP 结束标记以后万一意外加入了空格或者换行符, 会致使 PHP 开始输出这些空白,而脚本中此时并没有输出的意图。docker
凡是在一对开始和结束标记以外的内容都会被 PHP 解析器忽略,这使得 PHP 文件能够具有混合内容。数据库
<?php if ($expression == true): ?> This will show if the expression is true. <?php else: ?> Otherwise this will show. <?php endif; ?>
注释:PHP 语句以分号结尾(;)。PHP 代码块的关闭标签也会自动代表分号(所以在 PHP 代码块的最后一行没必要使用分号)。express
<!DOCTYPE html>
<html>
<body>
<?php // 这是单行注释 # 这也是单行注释 /* 这是多行注释块 它横跨了 多行 */ ?> </body> </html>
在 PHP 中,全部用户定义的函数、类和关键词(例如 if、else、echo 等等)都对大小写不敏感。
在下面的例子中,全部这三条 echo 语句都是合法的(等价):
<!DOCTYPE html>
<html>
<body>
<?php ECHO "Hello World!<br>"; echo "Hello World!<br>"; EcHo "Hello World!<br>"; ?> </body> </html>
不过在 PHP 中,全部变量都对大小写敏感。
在下面的例子中,只有第一条语句会显示 $color 变量的值(这是由于 $color、$COLOR 以及 $coLOR 被视做三个不一样的变量):
<!DOCTYPE html>
<html>
<body>
<?php $color="red"; echo "My car is " . $color . "<br>"; echo "My house is " . $COLOR . "<br>"; echo "My boat is " . $coLOR . "<br>"; ?> </body> </html>
使用转义字符来输出一些特殊的符号或者引号。
\t
\r
\'
$name = " World!"; echo "Hello{$name}";
echo "Hello World!";
$my_var = "Hello World!"; echo var_dump($my_var); echo strlen($my_var);
$myarr = array("one"=>"first", "two"=>"second", "three"=>"third" ); foreach($myarr as $key=>$value){ echo "key=".$key.", value=".$value; }
function myfun($title, $myvar="Moments"){ echo ">>>".$title." "; echo $myvar; echo " "; } myfun("如何使用函数", "Hello World!");
class MyClass{ var $myvar; function MyClass(){ $this->myvar = "Begin"; } function SetVar($temp){ $this->myvar = $temp; } function GetVar(){ return $this->myvar; } } $myclass = new MyClass; myfun("如何使用类", $myclass->GetVar()); $myclass->SetVar("Hello World!"); myfun("如何使用类", $myclass->GetVar());