我希望构建一个用PHP实现的栈。 我最初有这段代码:
class Stack
{
protected $stack;
protected $limit;
public function __construct($limit = 10) {
// initialize the stack
$this->stack = array();
// stack can only contain this many items
$this->limit = $limit;
}
public function push($item) {
// trap for stack overflow
if (count($this->stack) < $this->limit) {
// prepend item to the start of the array
array_unshift($this->stack, $item);
} else {
throw new RunTimeException('Stack is full!');
}
}
public function pop() {
if ($this->isEmpty()) {
// trap for stack underflow
throw new RunTimeException('Stack is empty!');
} else {
// pop item from the start of the array
return array_shift($this->stack);
}
}
public function top() {
return current($this->stack);
}
public function isEmpty() {
return empty($this->stack);
}
}
使用以下方式正常初始化类:
$stack = new Stack();
$stack->push(1);
$stack->push(2);
$stack->push(3);
$stack->push(4);
$stack->push(5);
这是正确并运行的。然而,我想通过以下方式初始化我的堆栈:
$stack = new Stack(array(1,2,3,4,5));
我该如何实现这个功能?
请注意,所有其他函数(例如 pop 和 push)都是函数式的。
array_push
пј€http://php.net/manual/en/function.array-push.phpпј‰е’Њ`array_pop`пј€http://us3.php.net/array_popпј‰е‡Ѕж•°е®ћзЋ°гЂ‚ - adeelxprivate
。请仅返回翻译后的文本。 - Raptor