基础语法
概述
理解PHP的语法对于编写干净、可读和可维护的代码至关重要。本章介绍了每个PHP开发者都应该了解的基本语法规则、约定和最佳实践。
PHP开始和结束标签
标准PHP标签
混合HTML和PHP
短的Echo标签(PHP 5.4+)
重要注意事项
- 始终使用
<?php标签(避免短标签<?) - 在纯PHP文件的末尾,结束
?>标签是可选的 - 在纯PHP文件中,开始标签前不要有空白
语句和表达式
语句
每个PHP语句必须以分号结尾:
表达式
表达式会计算为一个值:
大小写敏感性规则
区分大小写的元素
不区分大小写的元素
注释
单行注释
多行注释
文档注释(PHPDoc)
变量
变量声明和命名
可变变量
变量作用域
Constants
Defining Constants
Magic Constants
Class Constants
Operators
Arithmetic Operators
Assignment Operators
Comparison Operators
Logical Operators
Increment/Decrement Operators
String Operators
Control Structures Syntax
If-Else Statements
Alternative Syntax
String Syntax
Single vs Double Quotes
Heredoc Syntax
Nowdoc Syntax (PHP 5.3+)
Array Syntax
Array Declaration
Function Syntax
Function Declaration
Coding Standards and Best Practices
PSR-1 Basic Coding Standard
Naming Conventions
Code Formatting
Error Handling Syntax
Try-Catch Blocks
Next Steps
Now that you understand PHP's basic syntax, let's explore how PHP programs are structured in Program Structure.
Practice Exercises
- Create variables using different naming conventions and test case sensitivity
- Write a script using all types of operators
- Practice string interpolation with single quotes, double quotes, and heredoc
- Create functions with different parameter types and return values
- Write code following PSR-1 standards
Understanding these syntax fundamentals will make the rest of your PHP journey much smoother!