如果佇列是空的,dequeue() 會產生一個 'RuntimeException' 例外,訊息為「無法從空的資料結構中取出元素」。
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
SplQueue::dequeue — 從佇列中取出一個節點
此函式沒有參數。
已取出節點的值。
我認為這是一個有趣且有效的方法,可以將方法呼叫排隊,然後依序執行它們。這或許可以用作交易執行類別的基礎或其他用途。
<?php
$q = new SplQueue();
$q->setIteratorMode(SplQueue::IT_MODE_DELETE);
$q->enqueue(array("FooBar", "foo"));
$q->enqueue(array("FooBar", "bar"));
$q->enqueue(array("FooBar", "msg", "Hi there!"));
foreach ($q as $task) {
if (count($task) > 2) {
list($class, $method, $args) = $task;
$class::$method($args);
} else {
list($class, $method) = $task;
$class::$method();
}
}
class FooBar {
public static function foo() {
echo "FooBar::foo() called.\n";
}
public static function bar() {
echo "FooBar::bar() called.\n";
}
public static function msg($msg) {
echo "$msg\n";
}
}
?>
結果
FooBar::foo() called.
FooBar::bar() called.
Hi there!
<?php
$q = new SplQueue();
$q->setIteratorMode(SplQueue::IT_MODE_DELETE);
$q->enqueue('item 1');
$q->enqueue('item 2');
$q->enqueue('item 3');
$q->dequeue();
$q->dequeue();
foreach ($q as $item) {
echo $item;
}
//結果: item 3
$q->dequeue(); //致命錯誤:未捕獲的例外 'RuntimeException'
//訊息為 'Can't shift from an empty datastructure'
?>
我認為這是一個有趣且有效的方法,可以將方法呼叫排隊,然後依序執行它們。這或許可以用作交易執行類別的基礎或其他用途。
<?php
$q = new SplQueue();
$q->setIteratorMode(SplQueue::IT_MODE_DELETE);
$q->enqueue(array("FooBar", "foo"));
$q->enqueue(array("FooBar", "bar"));
$q->enqueue(array("FooBar", "msg", "Hi there!"));
foreach ($q as $task) {
if (count($task) > 2) {
list($class, $method, $args) = $task;
$class::$method($args);
} else {
list($class, $method) = $task;
$class::$method();
}
}
class FooBar {
public static function foo() {
echo "FooBar::foo() called.\n";
}
public static function bar() {
echo "FooBar::bar() called.\n";
}
public static function msg($msg) {
echo "$msg\n";
}
}
?>
結果
FooBar::foo() called.
FooBar::bar() called.
Hi there!