Reputation: 2556
<?php
$stack = new SplStack();
$stack->add(0, 'one');
$stack->add(1, 'two');
$stack->add(2, '2015');
echo "<pre>";
print_r($stack);
When i run this code, all items are stored an property called dllist
(i hope) and it's the expected result.
SplStack Object
(
[flags:SplDoublyLinkedList:private] => 6
[dllist:SplDoublyLinkedList:private] => Array
(
[0] => one
[1] => two
[2] => 2015
)
)
But i run the code below, works the same way that code above, why when i try, $stack[] = 'one';
why does not get an error? how php know that $stack[] = 'one';
should be stored in dllist
?
<?php
$stack = new SplStack();
$stack[] = 'one';
$stack[] = 2015;
$stack[] = 'two';
echo "<pre>";
print_r($stack);
I expected some errors like this statements:
<?php
$int = 2015;
$int[] = 300; //Warning: Cannot use a scalar value as an array in
$str = 'foo';
$str[] = 'foo'; //Fatal error: [] operator not supported for strings in
$obj = new stdClass();
$obj[] = 'new one'; //Fatal error: Cannot use object of type stdClass as array in
Upvotes: 2
Views: 2780
Reputation: 4211
Stack: In the pushdown stacks only two operations are allowed: push the item into the stack, and pop the item out of the stack. A stack is a limited access data structure - elements can be added and removed from the stack only at the top. push adds an item to the top of the stack, pop removes the item from the top. A helpful analogy is to think of a stack of books; you can remove only the top book, also you can add a new book on the top.
Queue: An excellent example of a queue is a line of students in the food court of the UC. New additions to a line made to the back of the queue, while removal (or serving) happens in the front. In the queue only two operations are allowed enqueue and dequeue. Enqueue means to insert an item into the back of the queue, dequeue means removing the front item. The picture demonstrates the FIFO access. The difference between stacks and queues is in removing. In a stack we remove the item the most recently added; in a queue, we remove the item the least recently added.!
For example stack
Last push element on top
last-in first-out (LIFO)
$q = new SplStack();
$q[] = 1;
$q[] = 2;
$q[] = 3;
$q->push(4);
$q->add(4,5);
$q->rewind();
while($q->valid()){
echo $q->current(),"\n";
$q->next();
}
?>
Output
5
4
3
2
1
For example queue
Last push element in bottom
first-in first-out (FIFO)
<?php
// Create a new empty queue
$gfg = new SplQueue();
$gfg[] = 1;
$gfg[] = 2;
$gfg[] = 3;
// Dequeue element
echo $gfg->dequeue() . "\n";
echo $gfg->dequeue() . "\n";
?>
Output:
1
2
Be careful someone asc someone desc
Upvotes: 2
Reputation: 1283
SplStack implements the interface ArrayAccess, causing the SplStack class to have array-features: http://php.net/manual/en/class.arrayaccess.php
Upvotes: 3