10分钟学会 PHP
PHP 是一种广泛使用的服务器端脚本语言,专为 Web 开发而设计。最初是为"个人主页"创建的,PHP 现在代表"PHP: Hypertext Preprocessor"。本教程涵盖 PHP 8.3+ 的特性,帮助你快速学习现代 PHP 开发。
1. 编写你的第一个 PHP 程序
我们从一个简单的程序开始。创建一个名为 hello.php
的文件,输入以下代码:
<?php
echo "Hello, World!";
?>
保存文件并使用 Web 服务器或 PHP CLI 运行它:
php hello.php
输出将是:
Hello, World!
这个简单的程序演示了 PHP 的基本输出功能。echo
语句用于显示文本。PHP 代码包含在 <?php
和 ?>
标签中。
2. 基本语法
PHP 语法简单直接,类似于 C 和 Perl。PHP 代码在服务器上执行,结果作为纯 HTML 发送到浏览器。
<?php
// This is a single-line comment
echo "Hello, World!";
/*
This is a multi-line comment
spanning multiple lines
*/
?>
PHP 中的基本语法规则:
- PHP 标签:PHP 代码必须包含在
<?php ... ?>
标签中 - 注释:单行注释使用
//
或#
,多行注释使用/* ... */
- 语句:以分号
;
结束 - 大小写敏感性:变量名区分大小写,但函数名不区分
- 变量:以
$
符号开头
<?php
$name = "John"; // Variable (case-sensitive)
$Name = "Jane"; // Different variable
echo $name; // Outputs: John
ECHO $Name; // Outputs: Jane (ECHO works same as echo)
?>
3. 变量和数据类型
在 PHP 中,变量是存储数据的容器。PHP 是一种松散类型的语言,意味着你不需要显式声明变量类型。
变量命名规则:
- 必须以
$
符号开头 - 可以包含字母、数字和下划线
- 不能以数字开头
- 区分大小写
PHP 的主要数据类型:
- 字符串(String):引号中的文本数据
- 整数(Integer):整数
- 浮点数(Float):小数
- 布尔值(Boolean):
true
或false
- 数组(Array):值的集合
- 对象(Object):类的实例
- NULL:表示无值
- 资源(Resource):对外部资源的引用
<?php
$name = "Alice"; // String
$age = 25; // Integer
$height = 5.8; // Float
$is_student = true; // Boolean
$grades = [90, 85, 92]; // Array
$data = null; // NULL
// Type checking
var_dump($name); // string(5) "Alice"
echo gettype($age); // integer
?>
3.1 字符串操作
字符串可以使用单引号或双引号定义,具有不同的行为:
<?php
$single = 'Single quote string';
$double = "Double quote string";
$name = "John";
$greeting = "Hello, $name!"; // Variable interpolation
$greeting2 = 'Hello, $name!'; // No interpolation
echo $greeting; // Hello, John!
echo $greeting2; // Hello, $name!
// String concatenation
$full_name = "John" . " " . "Doe";
$full_name .= " Jr."; // Append
// String functions
echo strlen($name); // String length: 4
echo strtoupper($name); // JOHN
echo strtolower($name); // john
echo substr($name, 0, 2); // Jo
?>
3.2 数组
PHP 支持索引数组、关联数组和多维数组:
<?php
// Indexed array
$fruits = ["apple", "banana", "orange"];
$numbers = array(1, 2, 3, 4, 5);
// Associative array
$person = [
"name" => "John",
"age" => 30,
"city" => "New York"
];
// Multidimensional array
$students = [
["name" => "Alice", "grade" => 90],
["name" => "Bob", "grade" => 85],
["name" => "Carol", "grade" => 92]
];
// Accessing arrays
echo $fruits[0]; // apple
echo $person["name"]; // John
echo $students[0]["grade"]; // 90
// Array functions
echo count($fruits); // 3
array_push($fruits, "grape"); // Add element
print_r($fruits); // Display array
?>
4. 运算符
PHP 提供各种运算符用于不同的操作:
4.1 算术运算符
<?php
$a = 10;
$b = 3;
echo $a + $b; // Addition: 13
echo $a - $b; // Subtraction: 7
echo $a * $b; // Multiplication: 30
echo $a / $b; // Division: 3.333...
echo $a % $b; // Modulus: 1
echo $a ** $b; // Exponentiation: 1000
?>
4.2 比较运算符
<?php
$x = 5;
$y = "5";
var_dump($x == $y); // true (equal value)
var_dump($x === $y); // false (identical type and value)
var_dump($x != $y); // false
var_dump($x !== $y); // true
var_dump($x > 3); // true
var_dump($x <= 5); // true
?>
4.3 逻辑运算符
<?php
$a = true;
$b = false;
var_dump($a && $b); // false (AND)
var_dump($a || $b); // true (OR)
var_dump(!$a); // false (NOT)
var_dump($a and $b); // false (AND, lower precedence)
var_dump($a or $b); // true (OR, lower precedence)
?>
5. 控制流
5.1 if 语句
<?php
$age = 20;
if ($age >= 18) {
echo "Adult";
} elseif ($age >= 13) {
echo "Teen";
} else {
echo "Child";
}
// Ternary operator
$status = ($age >= 18) ? "Adult" : "Minor";
echo $status;
// Null coalescing operator (PHP 7+)
$username = $_GET['user'] ?? 'guest';
?>
5.2 switch 语句
<?php
$day = "Monday";
switch ($day) {
case "Monday":
case "Tuesday":
case "Wednesday":
case "Thursday":
case "Friday":
echo "Weekday";
break;
case "Saturday":
case "Sunday":
echo "Weekend";
break;
default:
echo "Invalid day";
}
?>
5.3 循环
for 循环:
<?php
for ($i = 0; $i < 5; $i++) {
echo "Number: $i\n";
}
// foreach for arrays
$fruits = ["apple", "banana", "orange"];
foreach ($fruits as $fruit) {
echo $fruit . "\n";
}
// foreach with key-value pairs
$person = ["name" => "John", "age" => 30];
foreach ($person as $key => $value) {
echo "$key: $value\n";
}
?>
while 和 do-while 循环:
<?php
$count = 0;
while ($count < 3) {
echo "Count: $count\n";
$count++;
}
$num = 0;
do {
echo "Number: $num\n";
$num++;
} while ($num < 3);
?>
6. 函数
PHP 中的函数是执行特定任务的可重用代码块:
<?php
// Basic function
function greet($name) {
return "Hello, $name!";
}
echo greet("Alice");
// Function with default parameters
function calculate_area($length, $width = 1) {
return $length * $width;
}
echo calculate_area(5); // 5 (width defaults to 1)
echo calculate_area(5, 3); // 15
// Variable arguments
function sum(...$numbers) {
return array_sum($numbers);
}
echo sum(1, 2, 3, 4); // 10
// Anonymous functions (closures)
$multiply = function($a, $b) {
return $a * $b;
};
echo $multiply(4, 5); // 20
?>
6.1 变量作用域
<?php
$global_var = "I'm global";
function test_scope() {
global $global_var;
$local_var = "I'm local";
echo $global_var; // Accessible with 'global' keyword
echo $local_var; // Local to this function
}
test_scope();
// Static variables
function counter() {
static $count = 0;
$count++;
echo "Count: $count\n";
}
counter(); // Count: 1
counter(); // Count: 2
counter(); // Count: 3
?>
7. 面向对象编程
PHP 支持使用类和对象的面向对象编程:
<?php
class Person {
// Properties
private $name;
private $age;
public $city;
// Constructor
public function __construct($name, $age, $city = "Unknown") {
$this->name = $name;
$this->age = $age;
$this->city = $city;
}
// Methods
public function getName() {
return $this->name;
}
public function setAge($age) {
if ($age > 0) {
$this->age = $age;
}
}
public function getAge() {
return $this->age;
}
public function introduce() {
return "Hi, I'm {$this->name}, {$this->age} years old from {$this->city}";
}
}
// Creating objects
$person1 = new Person("John", 25, "New York");
$person2 = new Person("Jane", 30);
echo $person1->introduce();
echo $person2->getName();
?>
7.1 继承
<?php
class Animal {
protected $name;
protected $species;
public function __construct($name, $species) {
$this->name = $name;
$this->species = $species;
}
public function makeSound() {
return "{$this->name} makes a sound";
}
public function getInfo() {
return "{$this->name} is a {$this->species}";
}
}
class Dog extends Animal {
private $breed;
public function __construct($name, $breed) {
parent::__construct($name, "Dog");
$this->breed = $breed;
}
public function makeSound() {
return "{$this->name} barks";
}
public function fetch() {
return "{$this->name} fetches the ball";
}
}
$dog = new Dog("Buddy", "Golden Retriever");
echo $dog->getInfo(); // Buddy is a Dog
echo $dog->makeSound(); // Buddy barks
echo $dog->fetch(); // Buddy fetches the ball
?>
8. 错误处理
PHP 提供多种处理错误和异常的方法:
<?php
// Try-catch for exceptions
try {
$result = 10 / 0;
throw new Exception("Custom error message");
} catch (DivisionByZeroError $e) {
echo "Division by zero error: " . $e->getMessage();
} catch (Exception $e) {
echo "General error: " . $e->getMessage();
} finally {
echo "This always executes";
}
// Custom exception class
class CustomException extends Exception {
public function errorMessage() {
return "Custom error on line {$this->getLine()} in {$this->getFile()}: {$this->getMessage()}";
}
}
try {
throw new CustomException("Something went wrong!");
} catch (CustomException $e) {
echo $e->errorMessage();
}
?>
9. 文件操作
PHP 提供各种文件操作功能:
<?php
// Reading files
$content = file_get_contents("example.txt");
echo $content;
// Writing files
file_put_contents("output.txt", "Hello, PHP!");
// File operations with error handling
if (file_exists("data.txt")) {
$lines = file("data.txt", FILE_IGNORE_NEW_LINES);
foreach ($lines as $line) {
echo $line . "\n";
}
} else {
echo "File not found";
}
// Working with file handles
$handle = fopen("log.txt", "a");
if ($handle) {
fwrite($handle, "Log entry: " . date("Y-m-d H:i:s") . "\n");
fclose($handle);
}
?>
10. 处理表单和 HTTP
PHP 在处理 Web 表单和 HTTP 请求方面表现出色:
<?php
// HTML form (save as form.html)
/*
<form method="POST" action="process.php">
<input type="text" name="username" placeholder="Username">
<input type="email" name="email" placeholder="Email">
<input type="password" name="password" placeholder="Password">
<button type="submit">Submit</button>
</form>
*/
// Processing form data (process.php)
if ($_POST) {
$username = $_POST['username'] ?? '';
$email = $_POST['email'] ?? '';
$password = $_POST['password'] ?? '';
// Validation
if (empty($username) || empty($email) || empty($password)) {
echo "All fields are required";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email format";
} else {
// Process the data
echo "Welcome, " . htmlspecialchars($username);
// Hash password
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
// Save to database, etc.
}
}
// Working with GET parameters
$page = $_GET['page'] ?? 1;
$category = $_GET['category'] ?? 'all';
echo "Page: $page, Category: $category";
?>
11. 数据库操作
PHP 通常与数据库一起工作,特别是 MySQL:
<?php
// Database connection using PDO
try {
$pdo = new PDO(
"mysql:host=localhost;dbname=mydb;charset=utf8",
"username",
"password",
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);
// Prepared statements (secure)
$stmt = $pdo->prepare("SELECT * FROM users WHERE age > ? AND city = ?");
$stmt->execute([18, "New York"]);
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "User: " . $row['name'] . "\n";
}
// Insert data
$stmt = $pdo->prepare("INSERT INTO users (name, email, age) VALUES (?, ?, ?)");
$stmt->execute(["John Doe", "[email protected]", 25]);
echo "Last inserted ID: " . $pdo->lastInsertId();
} catch (PDOException $e) {
echo "Database error: " . $e->getMessage();
}
?>
12. 现代 PHP 特性(PHP 8.0+)
PHP 8.0+ 引入了许多现代特性:
<?php
// Named arguments (PHP 8.0+)
function createUser($name, $email, $age = 18, $active = true) {
return compact('name', 'email', 'age', 'active');
}
$user = createUser(
name: "John",
email: "[email protected]",
active: false
);
// Match expression (PHP 8.0+)
$status_code = 200;
$message = match($status_code) {
200, 201 => 'Success',
400 => 'Bad Request',
404 => 'Not Found',
500 => 'Server Error',
default => 'Unknown Status'
};
// Nullsafe operator (PHP 8.0+)
$user_name = $user?->profile?->name ?? 'Unknown';
// Constructor property promotion (PHP 8.0+)
class User {
public function __construct(
public string $name,
public string $email,
public int $age = 18,
private bool $active = true
) {}
public function isActive(): bool {
return $this->active;
}
}
$user = new User("John", "[email protected]", 25);
echo $user->name; // John
// Enums (PHP 8.1+)
enum Status {
case PENDING;
case APPROVED;
case REJECTED;
public function label(): string {
return match($this) {
Status::PENDING => 'Pending',
Status::APPROVED => 'Approved',
Status::REJECTED => 'Rejected',
};
}
}
$status = Status::PENDING;
echo $status->label(); // Pending
?>
13. 最佳实践和技巧
这里是一些重要的 PHP 最佳实践:
<?php
// 1. Always use PHP opening tags
// Good: <?php
// Avoid: <? (short tags)
// 2. Use prepared statements for database queries
// Prevents SQL injection
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$user_id]);
// 3. Validate and sanitize input
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
$name = htmlspecialchars($_POST['name'], ENT_QUOTES, 'UTF-8');
// 4. Use meaningful variable names
// Good:
$user_age = 25;
$is_active = true;
// Bad:
$a = 25;
$flag = true;
// 5. Handle errors gracefully
function divide($a, $b) {
if ($b == 0) {
throw new InvalidArgumentException("Division by zero");
}
return $a / $b;
}
// 6. Use type declarations (PHP 7+)
function calculateTotal(array $items): float {
return array_sum($items);
}
// 7. Organize code with namespaces
namespace App\Models;
class User {
// class implementation
}
// 8. Use composer for dependency management
// composer.json example:
/*
{
"require": {
"monolog/monolog": "^2.0"
},
"autoload": {
"psr-4": {
"App\\": "src/"
}
}
}
*/
?>
PHP 是一种强大而灵活的语言,非常适合 Web 开发。本教程涵盖了构建 PHP 应用程序所需的基本概念。实践这些概念,探索 Laravel 或 Symfony 等 PHP 框架,继续学习!