PHP Stack Implementation
data-structures, php, stack
Solution
Change your constructor as follows:
<?php
class Stack {
protected $stack;
protected $limit;
public function __construct($limit = 10, $initial = array()) {
// initialize the stack
$this->stack = $initial;
// 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);
}
}
/**
* This'll work as expected.
*/
$stack = new Stack();
$stack->push(1);
$stack->push(2);
$stack->push(3);
$stack->push(4);
$stack->push(5);
/**
* And this too.
*/
$stack = new Stack(10, array(1, 2, 3, 4, 5));
Just FYI, PHP has `array_push` (http://php.net/manual/en/function.array-push.php) and `array_pop` (https://www.php.net/array_pop) implementations.
Problem
I want to construct a stack implemented in PHP. Initially I have this code: ``` 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); } } ``` And initialize the class normally using this: ``` $stack = new Stack(); $stack->push(1); $stack->push(2); $stack->push(3); $stack->push(4); $stack->push(5); ``` This is correct and running. However, I want to initialize my stack with an initial value like this: ``` $stack = new Stack(array(1,2,3,4,5)); ``` How can I implement this? Note that all other functions (e.g pop and push) are functional.