STEP #1

(1/2)

此处切换ai服务商,可对比多家ai的回复,取最优解。

上一步下一步关闭
酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

php 面向对象 笔试题

# PHP面向对象编程笔试题 ## 基础概念题 1. 类与对象 ```php class User { public $name; public function __construct($name) { $this->name = $name; } public function greet() { return "Hello, " . $this->name; } } $user = new User("John"); echo $user->greet(); ``` 2. 继承 ```php class Animal { public function makeSound() { return "Some sound"; } } class Dog extends Animal { public function makeSound() { return "Bark"; } } $dog = new Dog(); echo $dog->makeSound(); ``` 3. 接口 ```php interface Logger { public function log($message); } class FileLogger implements Logger { public function log($message) { file_put_contents('log.txt', $message, FILE_APPEND); } } $logger = new FileLogger(); $logger->log("Error occurred"); ``` 4. 抽象类 ```php abstract class Shape { abstract public function area(); } class Circle extends Shape { private $radius; public function __construct($radius) { $this->radius = $radius; } public function area() { return pi() * $this->radius * $this->radius; } } $circle = new Circle(5); echo $circle->area(); ``` 5. 静态属性和方法 ```php class Counter { public static $count = 0; public static function increment() { self::$count++; } } Counter::increment(); Counter::increment(); echo Counter::$count; ``` ## 进阶概念题 6. 魔术方法 ```php class Product { private $data = []; public function __set($name, $value) { $this->data[$name] = $value; } public function __get($name) { return $this->data[$name] ?? null; } } $product = new Product(); $product->price = 100; echo $product->price; ``` 7. 命名空间 ```php namespace App\Models; class User { public $name; } $user = new \App\Models\User(); $user->name = "Alice"; ``` 8. Trait ```php trait Loggable { public function log($message) { echo "Logging: " . $message; } } class Order { use Loggable; } $order = new Order(); $order->log("Order created"); ``` 9. 自动加载 ```php spl_autoload_register(function ($class) { include $class . '.php'; }); $obj = new MyClass(); ``` 10. 异常处理 ```php class CustomException extends Exception {} try { throw new CustomException("Something went wrong"); } catch (CustomException $e) { echo "Caught exception: " . $e->getMessage(); } ``` ## 需要注意的逻辑点 - 在PHP中,类名不区分大小写但建议保持一致性 - 魔术方法如__construct、__get、__set等以双下划线开头 - 使用命名空间可以避免类名冲突,提高代码组织性 [2025-06-13 21:31:47 | AI写代码神器 | 717点数解答]

相关提问