php实现电梯
PHP实现电梯系统的基本思路
电梯系统的核心是模拟电梯的运行逻辑,包括上下移动、停靠楼层、响应内外请求等。PHP作为服务器端语言,可通过面向对象的方式实现电梯的类模型。
电梯类的基本结构
class Elevator {
private $currentFloor = 1; // 当前楼层
private $direction = 'idle'; // 运行方向: up/down/idle
private $requests = []; // 所有请求队列
private $maxFloor; // 最高楼层
public function __construct($maxFloor) {
$this->maxFloor = $maxFloor;
}
}
添加请求方法
public function addRequest($floor, $direction) {
if ($floor > 0 && $floor <= $this->maxFloor) {
$this->requests[] = [
'floor' => $floor,
'direction' => $direction
];
$this->processRequests();
}
}
请求处理逻辑
private function processRequests() {
if (empty($this->requests)) {
$this->direction = 'idle';
return;
}
// 按距离当前楼层的远近排序请求
usort($this->requests, function($a, $b) {
return abs($a['floor'] - $this->currentFloor) <=> abs($b['floor'] - $this->currentFloor);
});
$nextRequest = $this->requests[0];
$this->moveToFloor($nextRequest['floor']);
}
移动控制方法
private function moveToFloor($targetFloor) {
while ($this->currentFloor != $targetFloor) {
if ($this->currentFloor < $targetFloor) {
$this->direction = 'up';
$this->currentFloor++;
} else {
$this->direction = 'down';
$this->currentFloor--;
}
$this->checkStop();
sleep(1); // 模拟移动耗时
}
$this->stopAtFloor();
}
到达处理
private function stopAtFloor() {
$this->direction = 'idle';
// 移除已完成请求
$this->requests = array_filter($this->requests, function($req) {
return $req['floor'] != $this->currentFloor;
});
}
使用示例
$elevator = new Elevator(10);
$elevator->addRequest(5, 'up');
$elevator->addRequest(3, 'down');
扩展功能建议
-
增加电梯状态监控方法

public function getStatus() { return [ 'currentFloor' => $this->currentFloor, 'direction' => $this->direction, 'pendingRequests' => count($this->requests) ]; } -
实现多电梯调度系统
class ElevatorSystem { private $elevators = []; public function addElevator($elevator) { $this->elevators[] = $elevator; } public function dispatchRequest($floor, $direction) { // 实现智能分配算法 } } -
增加电梯容量限制和超载检测

-
添加紧急停止功能
-
实现楼层间的移动动画效果(需配合前端)
该实现提供了电梯系统的基本框架,可根据实际需求进一步扩展功能和完善逻辑。






