酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

php 面向对象 笔试题

# PHP面向对象编程笔试题 ## 基础概念题 1. 类和对象的区别是什么? - 类是对象的蓝图或模板,定义了对象的属性和方法 - 对象是类的实例,具有具体的属性值和可调用的方法 2. 解释PHP中的访问修饰符 - public: 在任何地方都可以访问 - protected: 只能在类内部和子类中访问 - private: 只能在定义它的类内部访问 3. 构造函数和析构函数的作用 - 构造函数`__construct()`在对象创建时自动调用 - 析构函数`__destruct()`在对象销毁时自动调用 ## 代码实现题 4. 实现一个简单的Person类 ```php class Person { private $name; private $age; public function __construct($name, $age) { $this->name = $name; $this->age = $age; } public function introduce() { return "My name is {$this->name} and I am {$this->age} years old."; } public function setName($name) { $this->name = $name; } public function getName() { return $this->name; } } ``` 5. 实现继承关系:Student继承Person ```php class Student extends Person { private $studentId; public function __construct($name, $age, $studentId) { parent::__construct($name, $age); $this->studentId = $studentId; } public function study($subject) { return "{$this->getName()} is studying {$subject}"; } public function getStudentId() { return $this->studentId; } } ``` ## 高级概念题 6. 解释抽象类和接口的区别 - 抽象类可以包含具体方法和抽象方法,接口只能有方法声明 - 类只能继承一个抽象类,但可以实现多个接口 - 抽象类可以有属性,接口不能有属性 7. 实现一个简单的接口和多态示例 ```php interface Shape { public function calculateArea(); } class Circle implements Shape { private $radius; public function __construct($radius) { $this->radius = $radius; } public function calculateArea() { return pi() * pow($this->radius, 2); } } class Rectangle implements Shape { private $width; private $height; public function __construct($width, $height) { $this->width = $width; $this->height = $height; } public function calculateArea() { return $this->width * $this->height; } } // 多态使用 function printArea(Shape $shape) { echo "Area: " . $shape->calculateArea() . "\n"; } $circle = new Circle(5); $rectangle = new Rectangle(4, 6); printArea($circle); // 输出圆的面积 printArea($rectangle); // 输出矩形的面积 ``` 8. 解释魔术方法`__get`和`__set`的作用 - `__get($name)`: 当访问不可访问属性时自动调用 - `__set($name, $value)`: 当给不可访问属性赋值时自动调用 ## 设计模式题 9. 实现单例模式 ```php class Database { private static $instance = null; private $connection; private function __construct() { $this->connection = new PDO("mysql:host=localhost;dbname=test", "user", "pass"); } public static function getInstance() { if (self::$instance === null) { self::$instance = new Database(); } return self::$instance; } public function getConnection() { return $this->connection; } private function __clone() {} private function __wakeup() {} } ``` 10. 解释依赖注入和控制反转(IoC) - 依赖注入是将依赖项通过构造函数、方法或属性传入 - 控制反转是将对象的创建和管理交给外部容器 ## 注意事项 1. 在PHP中,类名通常采用大驼峰命名法(PascalCase) 2. 方法名通常采用小驼峰命名法(camelCase) 3. 属性名通常使用小写字母和下划线组合(snake_case)或小驼峰命名法 [2025-06-13 21:35:11 | AI写代码神器 | 985点数解答]

相关提问