1. PHP 简介
PHP Hypertext Preprocessor
- web开发服务端解释型语言
2. PHP 基本语法
- 代码写在<?php 和 ?>标签中
- 短标签<? ?>
- 可以嵌入在HTML文档中,以.php扩展名结尾
- 如果文件中只有PHP代码,闭合标签 ?> 需被省略
- 功能执行语句以 ; 结尾 (一行语句时可省略)
- 结构定义语句如函数,类,接口,流程控制语句不需要;
<body>
<?php
echo "hello php";
?>
<p><? echo "Bonjour" ?></p>
</body>
2.1 注释
- 单行注释以//或#开始
// php comment 1
# php comment 2
- 多行注释用
/*...*/
2.2 大小写
- 变量名大小写敏感
- 关键字/类名/函数名大小写不敏感
3. PHP for循环,foreach循环,以及与JS比较
- for (JavaScript)
let animals=["cat","dog","pig","horse","dophin"];
for (let index = 0; index < animals.length; index++) {
const element = document.createElement("p");
element.textContent=animals[index];
console.log(element);
document.body.append(element);
}
- forEach (JavaScript)
animals.forEach(element=>{
const p = document.createElement("p");
p.textContent=element;
console.log(p);
document.body.append(p);
})
- for (PHP)
echo "<h3>Animals</h3>";
$animals = ["cat","dog","pig","horse","dophin"];
# PHP for loop
for ($i=0; $i < count($animals); $i++) {
echo "<p>$animals[$i]</p>";
}
- foreach (PHP)
# PHP foreach loop
foreach ($animals as $key => $value) {
echo "<p>$value</p>";
}
结果:
- foreach (PHP模板语法)
<body>
<!-- php 模板语法 代替 {} echo -->
<ol>
<?
$animals = ["cat","dog","pig","horse","dophin"];
foreach($animals as $animal):
?>
<li><?=$animal?></li>
<?endforeach?>
</ol>
</body>
4. 引入外部PHP文件
- require 或 include filename.php
- 公共内容如部分header, footer可以放进一个common文件夹中,然后在页面中之前引入,可以省略重复代码
config.php
<?php
$email = "12345@qq.com";
$address="1 Sturt Rd";
$post=5000;
引入config.php
<?php
require __DIR__."./config.php";
?>
使用config.php中声明的变量
<body>
<?=$email?>
<?=$address?>
<?=$post?>
</body>