<?php
class Stack
{
public $maxSize;
public $items = [];
public $top = 0;
public function __construct(array $stack, $maxSize){
$this->items = $stack;
$this->maxSize = $maxSize;
}
public function push($item){
if ($this->top === $this->maxSize){
throw new Exception("Stack overflow");
}
$this->items[$this->top] = $item;
$this->top++;
}
public function pop(){
if ($this->top === 0){
throw new Exception("Stack underflow");
}
$this->top--;
return $this->items[$this->top];
}
}
$items = [1, 2, 3, 4, 5];
$maxSize = 10;
$stack = new Stack($items, $maxSize);
$stack->push(6);
var_dump($stack);
$stack->pop();
var_dump($stack);
- Output for 7.1.0 - 7.1.33, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.26, 8.4.1 - 8.4.13
- object(Stack)#1 (3) {
["maxSize"]=>
int(10)
["items"]=>
array(5) {
[0]=>
int(6)
[1]=>
int(2)
[2]=>
int(3)
[3]=>
int(4)
[4]=>
int(5)
}
["top"]=>
int(1)
}
object(Stack)#1 (3) {
["maxSize"]=>
int(10)
["items"]=>
array(5) {
[0]=>
int(6)
[1]=>
int(2)
[2]=>
int(3)
[3]=>
int(4)
[4]=>
int(5)
}
["top"]=>
int(0)
}
preferences:
181.33 ms | 408 KiB | 5 Q