A Stack is a “last in, first out” or “LIFO” collection that only allows access to the value at the top of the structure and iterates in that order, destructively.
composer r ghosty/stack
This way you can create a new object of type Stakc
// app/Controllers/TestController.php
namespace App\Controllers;
use Ghosty\Component\Stack\Stack;
class TestController
{
public function show()
{
$Stack = new Stack();
}
}
The push method adds a new element to the stack.
// app/Controllers/TestController.php
namespace App\Controllers;
class TestController
{
public function show()
{
...
$Stack->push('1');
}
}
The pop method returns the last added stack element and removes it from the stack
// app/Controllers/TestController.php
namespace App\Controllers;
class TestController
{
public function show()
{
$Element = $Stack->pop(); // '1'
count($Stack); // 0;
}
}
The top method returns the last added stack element without removing it from the stack
// app/Controllers/TestController.php
namespace App\Controllers;
class TestController
{
public function show()
{
...
$Stack->push('1');
$Element = $Stack->top(); // '1'
count($Stack); // 1
}
}
The isEmpty method returns true if the stack is empty, false otherwise
// app/Controllers/TestController.php
namespace App\Controllers;
class TestController
{
public function show()
{
$empty = (new Stack())->push('1')->isEmpty(); // false
$empty = (new Stack())->isEmpty(); // true
}
}
The clear method clears the stack
// app/Controllers/TestController.php
namespace App\Controllers;
class TestController
{
public function show()
{
$Stack = (new Stack())->push('1');
$empty = $Stack->isEmpty(); // false
$empty = $Stack->clear()->isEmpty(); // true
}
}
The __toArray method returns all elements of the stack as an array
// app/Controllers/TestController.php
namespace App\Controllers;
class TestController
{
public function show()
{
$Stack = (new Stack())->push('1')->push('2');
$array = $Stack->__toArray(); // ['2', '1']
}
}
The count method returns the number of Stack elements, you can also use the standard PHP count method by passing an object of the Stack class to it
// app/Controllers/TestController.php
namespace App\Controllers;
class TestController
{
public function show()
{
$Stack = (new Stack())->push('1')->push('2');
$Count = $Stack->count(); // 2
$Count = count($Stack); // 2
}
}
Thanks to the AbstractStack class, you can create your own Stack class thanks to abstract class inheritance.
You can also override methods or write new ones in your class
// app/Stacks/TestStack.php
namespace App\Stacks;
use Ghosty\Component\Stack\AbstractStack;
class TestStack extends AbstractStack
{
/**
*@param string $item Item to push
*/
#[\Override]
public function push(mixed $item): static
{
if(!is_string($item))
{
throw new \Exception("Error");
}
return parent::push($item);
}
}