PHP面试题精选:从基础到高级全面解析
PHP作为最流行的服务器端脚本语言之一,在Web开发领域占据着重要地位。无论是初学者还是资深开发者,掌握PHP的核心概念和高级特性都至关重要。本文整理了常见的PHP面试题,从基础语法到高级特性,帮助读者全面准备PHP技术面试。
一、PHP基础语法与特性
1.1 变量与数据类型
PHP是一种弱类型语言,变量的数据类型不需要显式声明。PHP支持8种原始数据类型:
- 四种标量类型:boolean(布尔型)、integer(整型)、float(浮点型)、string(字符串)
- 两种复合类型:array(数组)、object(对象)
- 两种特殊类型:resource(资源)、NULL(无类型)
// 变量声明示例
$name = "John"; // 字符串
$age = 25; // 整型
$salary = 2500.50; // 浮点型
$is_employed = true; // 布尔型
$hobbies = array("reading", "sports"); // 数组
1.2 常量与魔术常量
常量使用define()函数定义,一旦定义就不能改变或取消定义。PHP还提供了一些魔术常量,它们的值会根据使用的位置而变化。
define("PI", 3.14159); // 定义常量
echo __FILE__; // 当前文件名
echo __LINE__; // 当前行号
echo __DIR__; // 当前目录
1.3 运算符
PHP支持各种运算符,包括算术运算符、比较运算符、逻辑运算符等。特别要注意的是三元运算符和太空船运算符(PHP 7+)。
// 太空船运算符示例
echo 1 <=> 1; // 0
echo 1 <=> 2; // -1
echo 2 <=> 1; // 1
二、字符串处理与正则表达式
2.1 字符串函数
PHP提供了丰富的字符串处理函数:
$str = "Hello World";
echo strlen($str); // 11
echo strpos($str, "World"); // 6
echo str_replace("World", "PHP", $str); // Hello PHP
echo substr($str, 0, 5); // Hello
2.2 正则表达式
正则表达式是处理字符串的强大工具,PHP支持PCRE(Perl兼容正则表达式)函数:
$pattern = '/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/';
$email = "test@example.com";
if (preg_match($pattern, $email)) {
echo "Valid email address";
} else {
echo "Invalid email address";
}
三、数组操作与处理
3.1 数组类型与创建
PHP支持索引数组、关联数组和多维数组:
// 索引数组
$fruits = array("Apple", "Banana", "Orange");
// 关联数组
$person = array(
"name" => "John",
"age" => 25,
"city" => "New York"
);
// 多维数组
$employees = array(
array("name" => "John", "salary" => 5000),
array("name" => "Jane", "salary" => 6000)
);
3.2 数组函数
PHP提供了大量数组处理函数:
$numbers = array(1, 2, 3, 4, 5);
// 数组遍历
foreach($numbers as $number) {
echo $number . " ";
}
// 数组操作
echo count($numbers); // 5
echo in_array(3, $numbers); // true
array_push($numbers, 6); // 添加元素
$last = array_pop($numbers); // 移除最后一个元素
四、面向对象编程
4.1 类与对象
PHP支持面向对象编程,包括类、对象、属性、方法等概念:
class Person {
// 属性
public $name;
private $age;
protected $email;
// 构造方法
public function __construct($name, $age, $email) {
$this->name = $name;
$this->age = $age;
$this->email = $email;
}
// 方法
public function getAge() {
return $this->age;
}
// 静态方法
public static function sayHello() {
echo "Hello!";
}
}
// 创建对象
$person = new Person("John", 25, "john@example.com");
echo $person->name; // John
echo $person->getAge(); // 25
Person::sayHello(); // Hello!
4.2 继承与多态
PHP支持类的继承和多态:
class Employee extends Person {
private $salary;
public function __construct($name, $age, $email, $salary) {
parent::__construct($name, $age, $email);
$this->salary = $salary;
}
public function getSalary() {
return $this->salary;
}
// 方法重写
public function getAge() {
return "Age: " . parent::getAge();
}
}
$employee = new Employee("Jane", 30, "jane@example.com", 5000);
echo $employee->getAge(); // Age: 30
五、错误处理与异常
5.1 错误处理
PHP提供了多种错误处理机制:
// 错误报告设置
error_reporting(E_ALL);
ini_set('display_errors', 1);
// 自定义错误处理函数
set_error_handler(function($errno, $errstr, $errfile, $errline) {
echo "Error: [$errno] $errstr in $errfile on line $errline";
return true;
});
// 触发错误
trigger_error("Custom error message", E_USER_WARNING);
5.2 异常处理
PHP使用try-catch块处理异常:
class CustomException extends Exception {
public function errorMessage() {
return "Error on line {$this->getLine()} in {$this->getFile()}: {$this->getMessage()}";
}
}
try {
$age = -5;
if ($age < 0) {
throw new CustomException("Age cannot be negative");
}
} catch (CustomException $e) {
echo $e->errorMessage();
} catch (Exception $e) {
echo $e->getMessage();
} finally {
echo "Execution completed.";
}
六、文件操作与处理
6.1 文件读写
PHP提供了多种文件操作函数:
// 写入文件
$file = fopen("test.txt", "w");
fwrite($file, "Hello World\n");
fclose($file);
// 读取文件
$file = fopen("test.txt", "r");
echo fread($file, filesize("test.txt"));
fclose($file);
// 简化方式
file_put_contents("test.txt", "New content");
echo file_get_contents("test.txt");
6.2 文件上传
处理文件上传是Web开发中的常见需求:
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['file'])) {
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
// 检查文件类型
if($imageFileType != "jpg" && $imageFileType != "png") {
echo "Sorry, only JPG & PNG files are allowed.";
$uploadOk = 0;
}
// 检查文件大小
if ($_FILES["file"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
if ($uploadOk == 1) {
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
echo "The file ". htmlspecialchars(basename($_FILES["file"]["name"])). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
七、数据库操作
7.1 MySQLi扩展
使用MySQLi进行数据库操作:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// 预处理语句防止SQL注入
$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$
评论框