简体   繁体   English

如何从数组创建 PHP SplStack

[英]How to create PHP SplStack from array

I'm wondering if there is an easy way to create SplStack from an array.我想知道是否有一种从数组创建SplStack的简单方法。 Sure I can write a simple function that will do that:当然,我可以编写一个简单的 function 来做到这一点:

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?有没有办法直接从数组创建堆栈?

The documentation doesn't suggest any method to use, nor does it specify that the constructor can be used through the SplDoublyLinkedList.该文档没有建议使用任何方法,也没有指定可以通过 SplDoublyLinkedList 使用构造函数。

Since, really, all the SplStack is just a SplDoublyLinkedList wrapper, you could easily create a Facade to achieve this.因为,实际上,所有 SplStack 只是一个 SplDoublyLinkedList 包装器,您可以轻松地创建一个 Facade 来实现这一点。

Create a simple interface for future extendability and testability:为未来的可扩展性和可测试性创建一个简单的接口:

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

Extend the SplStack functionality for coupling.扩展SplStack的耦合功能。

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.org3v4l.org查看它的工作情况

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM