Skip to content

基础语法

概述

理解PHP的语法对于编写干净、可读和可维护的代码至关重要。本章介绍了每个PHP开发者都应该了解的基本语法规则、约定和最佳实践。

PHP开始和结束标签

标准PHP标签

php
<?php
// PHP代码在这里
?>

混合HTML和PHP

php
<!DOCTYPE html>
<html>
<body>
    <h1><?php echo "欢迎使用PHP!"; ?></h1>
    <p>今天是 <?php echo date('Y-m-d'); ?></p>
</body>
</html>

短的Echo标签(PHP 5.4+)

php
<h1><?= $title ?></h1>
<!-- 等价于: -->
<h1><?php echo $title; ?></h1>

重要注意事项

  • 始终使用<?php标签(避免短标签<?
  • 在纯PHP文件的末尾,结束?>标签是可选的
  • 在纯PHP文件中,开始标签前不要有空白

语句和表达式

语句

每个PHP语句必须以分号结尾:

php
<?php
echo "Hello, World!";        // 语句
$name = "John";              // 语句
$result = 5 + 3;             // 语句
?>

表达式

表达式会计算为一个值:

php
<?php
$a = 5;                      // 5是一个表达式
$b = $a + 3;                 // $a + 3是一个表达式
$c = ($a > $b) ? $a : $b;    // 三元表达式
?>

大小写敏感性规则

区分大小写的元素

php
<?php
// 变量区分大小写
$name = "John";
$Name = "Jane";      // 不同的变量
$NAME = "Bob";       // 不同的变量

// 类名区分大小写
class MyClass {}
$obj1 = new MyClass();    // 正确
// $obj2 = new myclass(); // 错误
?>

不区分大小写的元素

php
<?php
// 函数名不区分大小写
function myFunction() {
    return "Hello";
}

echo myFunction();    // 可以工作
echo MyFunction();    // 也可以工作
echo MYFUNCTION();    // 也可以工作

// 关键字不区分大小写
IF (true) {           // 可以工作(但不推荐)
    ECHO "Hello";     // 可以工作(但不推荐)
}
?>

注释

单行注释

php
<?php
// 这是一个单行注释
echo "Hello"; // 行末注释

# 这也是一个单行注释(Unix风格)
$name = "John"; # 另一个注释
?>

多行注释

php
<?php
/*
这是一个多行注释
它可以跨越多行
用于更长的解释
*/

$result = 5 * 3; /* 内联多行注释 */
?>

文档注释(PHPDoc)

php
<?php
/**
 * 计算矩形的面积
 * 
 * @param float $width  矩形的宽度
 * @param float $height 矩形的高度
 * @return float 矩形的面积
 */
function calculateArea($width, $height) {
    return $width * $height;
}
?>

变量

变量声明和命名

php
<?php
// 有效的变量名
$name = "John";
$_age = 25;
$firstName = "Jane";
$user_id = 123;
$isActive = true;
$HTML = "<h1>Title</h1>";

// 无效的变量名(会导致错误)
// $2name = "Error";     // 不能以数字开头
// $first-name = "Error"; // 不能包含连字符
// $class = "Error";      // 'class'是保留字
?>

可变变量

php
<?php
$var = "name";
$name = "John";

echo $$var; // 输出:John(等价于$name)

// 更复杂的示例
$prefix = "user_";
$user_name = "Alice";
$user_age = 30;

$field = "name";
echo ${$prefix . $field}; // 输出:Alice
?>

变量作用域

php
<?php
$globalVar = "我是全局变量";

function testScope() {
    $localVar = "我是局部变量";
    
    // 访问全局变量
    global $globalVar;
    echo $globalVar;
    
    // 或者使用$GLOBALS超全局变量
    echo $GLOBALS['globalVar'];
}

// 静态变量
function counter() {
    static $count = 0;
    $count++;
    echo $count;
}

counter(); // 1
counter(); // 2
counter(); // 3
?>

Constants

Defining Constants

php
<?php
// Using define() function
define("SITE_NAME", "My Website");
define("MAX_USERS", 100);
define("PI", 3.14159);

// Using const keyword (PHP 5.3+)
const APP_VERSION = "1.0.0";
const DEBUG_MODE = true;

echo SITE_NAME;    // My Website
echo MAX_USERS;    // 100
?>

Magic Constants

php
<?php
echo __FILE__;     // Full path of current file
echo __DIR__;      // Directory of current file
echo __LINE__;     // Current line number
echo __FUNCTION__; // Current function name
echo __CLASS__;    // Current class name
echo __METHOD__;   // Current method name
echo __NAMESPACE__; // Current namespace
?>

Class Constants

php
<?php
class MathConstants {
    const PI = 3.14159;
    const E = 2.71828;
    
    public function getCircumference($radius) {
        return 2 * self::PI * $radius;
    }
}

echo MathConstants::PI; // 3.14159
?>

Operators

Arithmetic Operators

php
<?php
$a = 10;
$b = 3;

echo $a + $b;  // 13 (addition)
echo $a - $b;  // 7  (subtraction)
echo $a * $b;  // 30 (multiplication)
echo $a / $b;  // 3.333... (division)
echo $a % $b;  // 1  (modulus)
echo $a ** $b; // 1000 (exponentiation, PHP 5.6+)
?>

Assignment Operators

php
<?php
$x = 10;        // Basic assignment
$x += 5;        // $x = $x + 5 (15)
$x -= 3;        // $x = $x - 3 (12)
$x *= 2;        // $x = $x * 2 (24)
$x /= 4;        // $x = $x / 4 (6)
$x %= 5;        // $x = $x % 5 (1)

$str = "Hello";
$str .= " World"; // String concatenation assignment
echo $str;        // "Hello World"
?>

Comparison Operators

php
<?php
$a = 5;
$b = "5";

var_dump($a == $b);  // true (equal value)
var_dump($a === $b); // false (identical - same value and type)
var_dump($a != $b);  // false (not equal)
var_dump($a !== $b); // true (not identical)
var_dump($a < 10);   // true (less than)
var_dump($a > 3);    // true (greater than)
var_dump($a <= 5);   // true (less than or equal)
var_dump($a >= 5);   // true (greater than or equal)
?>

Logical Operators

php
<?php
$x = true;
$y = false;

var_dump($x && $y);  // false (AND)
var_dump($x || $y);  // true (OR)
var_dump(!$x);       // false (NOT)
var_dump($x and $y); // false (AND - lower precedence)
var_dump($x or $y);  // true (OR - lower precedence)
var_dump($x xor $y); // true (XOR - exclusive or)
?>

Increment/Decrement Operators

php
<?php
$i = 5;

echo ++$i; // 6 (pre-increment)
echo $i++; // 6 (post-increment, then $i becomes 7)
echo --$i; // 6 (pre-decrement)
echo $i--; // 6 (post-decrement, then $i becomes 5)
?>

String Operators

php
<?php
$first = "Hello";
$second = "World";

$result = $first . " " . $second; // Concatenation
echo $result; // "Hello World"

$first .= " " . $second; // Concatenation assignment
echo $first; // "Hello World"
?>

Control Structures Syntax

If-Else Statements

php
<?php
$score = 85;

if ($score >= 90) {
    $grade = "A";
} elseif ($score >= 80) {
    $grade = "B";
} elseif ($score >= 70) {
    $grade = "C";
} else {
    $grade = "F";
}

// Ternary operator
$status = ($score >= 60) ? "Pass" : "Fail";

// Null coalescing operator (PHP 7+)
$username = $_GET['user'] ?? 'guest';
?>

Alternative Syntax

php
<?php if ($condition): ?>
    <p>This is displayed if condition is true</p>
<?php else: ?>
    <p>This is displayed if condition is false</p>
<?php endif; ?>

String Syntax

Single vs Double Quotes

php
<?php
$name = "John";

// Single quotes - literal string
$message1 = 'Hello, $name!';        // "Hello, $name!"
$message2 = 'It\'s a nice day';     // Escape single quote

// Double quotes - variable interpolation
$message3 = "Hello, $name!";        // "Hello, John!"
$message4 = "He said \"Hello\"";    // Escape double quote
?>

Heredoc Syntax

php
<?php
$name = "John";
$html = <<<HTML
<div class="user">
    <h2>Welcome, $name!</h2>
    <p>This is a heredoc string.</p>
</div>
HTML;

echo $html;
?>

Nowdoc Syntax (PHP 5.3+)

php
<?php
$text = <<<'TEXT'
This is a nowdoc string.
Variables like $name are not interpolated.
It's like single quotes but for multi-line strings.
TEXT;

echo $text;
?>

Array Syntax

Array Declaration

php
<?php
// Old syntax
$fruits1 = array("apple", "banana", "orange");

// New syntax (PHP 5.4+)
$fruits2 = ["apple", "banana", "orange"];

// Associative array
$person = [
    "name" => "John",
    "age" => 30,
    "city" => "New York"
];

// Mixed array
$mixed = [
    0 => "first",
    "key" => "value",
    1 => "second"
];
?>

Function Syntax

Function Declaration

php
<?php
// Basic function
function greet($name) {
    return "Hello, " . $name;
}

// Function with default parameters
function createUser($name, $role = "user", $active = true) {
    return [
        "name" => $name,
        "role" => $role,
        "active" => $active
    ];
}

// Function with type hints (PHP 7+)
function add(int $a, int $b): int {
    return $a + $b;
}

// Variable function
$functionName = "greet";
echo $functionName("John"); // Calls greet("John")
?>

Coding Standards and Best Practices

PSR-1 Basic Coding Standard

php
<?php
// File should start with <?php tag
// No closing ?> tag in PHP-only files

namespace MyProject\Models;

use DateTime;
use Exception;

class UserModel
{
    const STATUS_ACTIVE = 1;
    
    public $name;
    private $email;
    
    public function getName()
    {
        return $this->name;
    }
    
    public function setEmail($email)
    {
        $this->email = $email;
    }
}
?>

Naming Conventions

php
<?php
// Variables and functions: camelCase
$userName = "john_doe";
$isActive = true;

function getUserById($id) {
    // Function body
}

// Constants: UPPER_CASE
const MAX_LOGIN_ATTEMPTS = 3;
define('API_VERSION', '1.0');

// Classes: PascalCase
class UserController {
    // Class body
}

// Private/protected properties: prefix with underscore (optional)
class MyClass {
    private $_privateProperty;
    protected $_protectedProperty;
    public $publicProperty;
}
?>

Code Formatting

php
<?php
// Proper indentation (4 spaces recommended)
if ($condition) {
    if ($anotherCondition) {
        doSomething();
    }
}

// Proper spacing
$result = $a + $b * $c;
$array = ['item1', 'item2', 'item3'];

// Line length (80-120 characters max)
$longVariableName = someFunction($parameter1, $parameter2, 
                                $parameter3, $parameter4);
?>

Error Handling Syntax

Try-Catch Blocks

php
<?php
try {
    $result = riskyOperation();
    echo $result;
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
} finally {
    // Cleanup code (PHP 5.5+)
    cleanup();
}
?>

Next Steps

Now that you understand PHP's basic syntax, let's explore how PHP programs are structured in Program Structure.

Practice Exercises

  1. Create variables using different naming conventions and test case sensitivity
  2. Write a script using all types of operators
  3. Practice string interpolation with single quotes, double quotes, and heredoc
  4. Create functions with different parameter types and return values
  5. Write code following PSR-1 standards

Understanding these syntax fundamentals will make the rest of your PHP journey much smoother!

本站内容仅供学习和研究使用。