the SplStack is simply a SplDoublyLinkedList with an iteration mode IT_MODE_LIFO and IT_MODE_KEEP
(PHP 5 >= 5.3.0, PHP 7)
The SplStack class provides the main functionalities of a stack implemented using a doubly linked list.
the SplStack is simply a SplDoublyLinkedList with an iteration mode IT_MODE_LIFO and IT_MODE_KEEP
<?php
/**
* Description of Stack
*
* (c) lsroudi <http://lsroudi.com/> <lsroudi@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
class Stack {
private $splstack;
function __construct(\SplStack $splstack)
{
$this->splstack = $splstack;
}
public function calculateSomme()
{
if ($this->splstack->count() > 1){
$val1 = $this->splstack->pop();
$val2 = $this->splstack->pop();
$val = $val1 + $val2;
$this->splstack->push($val);
$this->calculateSomme();
}
}
/**
*
* @return integer
*/
public function displaySomme()
{
$result = $this->splstack->pop();
return $result;
}
}
$splstack = new \SplStack();
$splstack->push(10);
$splstack->push(10);
$splstack->push(10);
$splstack->push(10);
$splstack->push(10);
$splstack->push(10);
$splstack->push(10);
$splstack->push(10);
$splstack->push(10);
$splstack->push(10);
$splstack->push(10);
$splstack->push(10);
$splstack->push(10);
$splstack->push(10);
$splstack->push(10);
$stack = new Stack($splstack);
$stack->calculateSomme();
die(var_dump($stack->displaySomme())); // 150
?>
source : https://github.com/lsroudi/OOPWithSPL/blob/master/Stack/Stack.php
<?php
# Think of the stack as an array reversed, where the last element has index zero
$stack = new SplStack();
$stack->push('a');
$stack->push('b');
$stack->push('c');
$stack->offsetSet(0, 'C'); # the last element has index zero
$stack->rewind();
while( $stack->valid() )
{
echo $stack->current(), PHP_EOL;
$stack->next();
}
/*
OUTPUT
****************************
C
b
a
*/
?>