PHP - Ds\PriorityQueue::__construct() 函式



PHP 的 Ds\PriorityQueue::__construct() 函式是一個內建函式,用於建立一個新的優先順序佇列例項。此函式不接受任何引數,也不返回值。

語法

以下是 PHP Ds\PriorityQueue::__construct() 函式的語法:

public Ds\PriorityQueue::__construct( void )

引數

此函式不接受任何引數。

返回值

此函式不返回值。它初始化一個新的 Ds\PriorityQueue 物件例項。

PHP 版本

__construct() 函式從 Ds 擴充套件的 1.0.0 版本開始可用。

示例 1

以下是如何使用 PHP Ds\PriorityQueue::__construct() 函式建立新的優先順序佇列的基本示例。

<?php
   // Create a new instance of PriorityQueue
   $pqueue = new \Ds\PriorityQueue();

   // Output the structure and contents of the PriorityQueue
   var_dump($pqueue);
?>

輸出

以下是以下程式碼的輸出:

object(Ds\PriorityQueue)#1 (0) {
}

示例 2

在下面的 PHP 程式碼中,我們將使用 __construct() 函式建立一個簡單的優先順序佇列並在其中新增元素。

<?php
   // Create a new instance of PriorityQueue
   $queue = new \Ds\PriorityQueue();

   // Insert the elements in queue
   $queue->push("Task 1", 1); 
   $queue->push("Task 2", 2); 
   $queue->push("Task 3", 3); 
   
   foreach ($queue as $task) {
       echo $task . "\n";
   }
?> 

輸出

這將生成以下輸出:

Task 3
Task 2
Task 1

示例 3

現在下面的程式碼,使用 __construct() 函式新增具有不同優先順序的項,並跟蹤檢索順序。

<?php
   // Create a new instance of PriorityQueue
   $queue = new \Ds\PriorityQueue();

   $queue->push("Low priority task", 1);
   $queue->push("Medium priority task", 5);
   $queue->push("High priority task", 10);
   
   foreach ($queue as $task) {
       echo $task . "\n";
   }
?> 

輸出

這將建立以下輸出:

High priority task
Medium priority task
Low priority task

示例 4

在以下示例中,我們使用 __construct() 函式在優先順序佇列中儲存物件。

<?php
   // Create a class for task
   class Task {
      public $name;
      public function __construct($name) {
          $this->name = $name;
      }
  }
  
  // Create a new instance of PriorityQueue
  $queue = new \Ds\PriorityQueue();
  
  // Insert the elements in the queue
  $queue->push(new Task("Task A"), 2);
  $queue->push(new Task("Task B"), 1);
  $queue->push(new Task("Task C"), 3);
  
  foreach ($queue as $task) {
      echo $task->name . "\n";
  }
?> 

輸出

以下是以上程式碼的輸出:

Task C
Task A
Task B

總結

Ds\PriorityQueue::__construct() 函式是 PHP 中一個內建方法,用於建立例項。我們已經演示了不同的示例,說明了如何建立優先順序佇列、新增具有優先順序的元素,然後遍歷佇列以根據其優先順序獲取元素。

php_function_reference.htm
廣告