Home > Enterprise >  How to create PHP SplStack from array
How to create PHP SplStack from array

Time:12-11

I'm wondering if there is an easy way to create SplStack from an array. Sure I can write a simple function that will do that:

function stackFromArray(array $array): SplStack
{
    $stack = new SplStack();
    foreach ($array as $item) {
        $stack->push($item);
    }

    return $stack;
}

However, I don't like this approach, because I have to iterate over the array and push items one by one. Is there a way to create a stack directly from the array?

CodePudding user response:

The documentation doesn't suggest any method to use, nor does it specify that the constructor can be used through the SplDoublyLinkedList.

Since, really, all the SplStack is just a SplDoublyLinkedList wrapper, you could easily create a Facade to achieve this.

Create a simple interface for future extendability and testability:

interface SplStackFacadeInterface
{ 
    public static function fromArray(array $arr);
}

Extend the SplStack functionality for coupling.

class SplStackFacade extends SplStack implements SplStackFacadeInterface
{
    public static function fromArray(array $arr): SplStack
    {
        $splStack = new self();
        array_map([$splStack, 'push'], $arr);
        return $splStack;
    }
}

Then just use it like so:

$stack = SplStackFacade::fromArray([1, 2, 3, 4]);

See it working over at 3v4l.org

  • Related