PHP.mk документација

SplQueue

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

class.splqueue.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека class.splqueue.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
SplQueue

Референца за `class.splqueue.php` со подобрена типографија и навигација.

class.splqueue.php

Класата SplQueue

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

Вовед

Класата SplQueue ги обезбедува главните функционалности на опашка имплементирана со двојно поврзана листа со поставување на режимот на итератор на SplDoublyLinkedList::IT_MODE_FIFO.

Синопсис на класата

class SplQueue extends SplDoublyLinkedList {
/* Наследни константи */
/* Методи */
public dequeue(): mixed
public enqueue(mixed $value): void
/* Наследени методи */
public SplDoublyLinkedList::add(int $index, mixed $value): void
}

Примери

Пример #1 SplQueue example

<?php
$q
= new SplQueue();
$q[] = 1;
$q[] = 2;
$q[] = 3;
foreach (
$q as $elem) {
echo
$elem."\n";
}
?>

Пример #1 Пример што покажува затворачка ознака што го опфаќа последниот нов ред

1
2
3

Пример #2 Ефикасно ракување со задачи со SplQueue

<?php
$q
= new SplQueue();
$q->setIteratorMode(SplQueue::IT_MODE_DELETE);
// ... enqueue some tasks on the queue ...
// process them
foreach ($q as $task) {
// ... process $task ...
// add new tasks on the queue
$q[] = $newTask;
// ...
}
?>

Содржина

Белешки од корисници 6 белешки

Ману Манџунат
12 години пред
SplQueue inherits from SplDoublyLinkedList. So, objects of SplQueue support methods push() and pop(). But please be advised that if you use push() and pop() methods on a SplQueue object, it behaves like a stack rather than a queue.

For example:

$q = new SplQueue();
$q->push(1);
$q->push(2);
$q->push(3);
$q->pop();
print_r($q);

Above code returns:

SplQueue Object
(
    [flags:SplDoublyLinkedList:private] => 4
    [dllist:SplDoublyLinkedList:private] => Array
        (
            [0] => 1
            [1] => 2
        )
)

Note that 3 got popped and *not* 1.

So, please make sure that you use only enqueue() and dequeue() methods on a SplQueue object and *not* push() and pop().
booleantype на ya dot ru
пред 4 години
Answer to Manu Manjunath post (#114336).

IMO, pop() works as expected.

There are 2 main groups of methods:

1) pop() & push() are inherited from SplDoublyLinkedList and can be applied to SplStack as well as SplQueue (ie are "faceless"). It isn't about stack or queue; it's just about deleting / adding element to the end of the list;

2) the same situation with shift() & unshift(): it is just about adding an element to the beginning of the list, and doesn't matter, if we use it on SplStack or SplQueue.

So, yes, $q->pop(); will remove *last* element from SplQueue $q.

But enqueue() & dequeue() *are about* SplQueue. FIFO principle is realized by these methods, which were implemented *exactly* for queue purpose:
- enqueue() adds an element to the end of the queue and is alias for "faceless" push() (FI...);
- dequeue() removes element from the beginning of the queue and is alias for "faceless" shift() (...FO).

If you want to delete *next in line* element from *queue*, use dequeue().
If you want to delete *last* element from the list (doesn't matter, if it's queue or stack), use pop().
MrStonedOne
пред 11 години
You can use shift/unshift and push/pop to dequeue/undequeue and queue/unqueue respectively. Really handy for those applications that use sockets where you might not know you can't send data until you attempt to.

for example, this is a function for an application that will un-dequeue the remainder of the data if socket_write indicated it did not write the entire contents of the provided data.

<?php
function processSendQueue($socket, $sendQueue) {
    while (!$sendQueue->isEmpty()) {
                            //shift() is the same as dequeue()
        $senditem = $sendQueue->shift();

        //returns the number of bytes written.
        $rtn = socket_write($socket, $senditem);
        if ($rtn === false) {
            $sendQueue->unshift($senditem);
            throw new exception("send error: " . socket_last_error($socket));
            return;
        }
        if ($rtn < strlen($senditem) {
            $sendQueue->unshift(substr($senditem, $rtn);
            break;
        }
    }
}
?>
Premysl Karbula
пред 8 години
<?php
  
$queue = new SplQueue();
$queue->enqueue('A');
$queue->enqueue('B');
$queue->enqueue('C');

$queue->rewind();
while($queue->valid()){
    echo $queue->current(),"\n";
    $queue->next();
}

print_r($queue);
$queue->dequeue(); //remove first one
print_r($queue);

?>
Output

A
B
C
SplQueue Object
(
    [flags:SplDoublyLinkedList:private] => 4
    [dllist:SplDoublyLinkedList:private] => Array
        (
            [0] => A
            [1] => B
            [2] => C
        )

)
SplQueue Object
(
    [flags:SplDoublyLinkedList:private] => 4
    [dllist:SplDoublyLinkedList:private] => Array
        (
            [0] => B
            [1] => C
        )

)
Стингус
пред 9 години
Take care that SplQueue::valid() is not returning true if the queue has nodes. Use isEmpty() instead:

$queue = new SplQueue();
$queue->enqueue('A');
$queue->enqueue('B');
$queue->enqueue('C');
var_dump($queue->valid()); // false
var_dump(!$queue->isEmpty()); // true
mostefa dot medjahed dot pro на gmail dot com
пред 5 години
As was said before, the push () and pop () methods on a SplQueue object, its behave like a stack rather than a queue.

Knowing that the enqueue () and dequeue () methods are respectively aliases of push () and shift () methods, we can also use SplQueue :: push () and SplQueue :: shift () for the same purpose as SplQueue :: enqueue and SplQueue :: dequeue.
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.