PHP - FileInfo 建構函式



PHP FileInfo 的 construct() 函式是用於建立 FileInfo 物件的構造方法。因此,它初始化物件並準備使用。此方法不返回值。

但是,您可以透過呼叫其方法(例如 file())從 FileInfo 物件獲取重要詳細資訊。

語法

以下是 PHP FileInfo construct() 函式的語法:

public finfo::__construct([ int $options = FILEINFO_NONE [, string $magic_file = NULL ]] )

引數

以下是 construct() 函式的引數:

  • $options - 它為 FileInfo 物件設定各種選項。其預設值為 FILEINFO_NONE。

  • $magic_file - 它是自定義 magic 檔案的路徑。

返回值

construct() 函式不返回值。

PHP 版本

construct() 函式首次引入到核心 PHP 5.3.0 中,並且在 PHP 5、PHP 7 和 PHP 8 中都能輕鬆使用。

示例 1

以下是 PHP FileInfo construct() 函式的基本示例,用於建立 FileInfo 物件以獲取檔案的 MIME 型別。

<?php
   // Create a new FileInfo object
   $finfo = new finfo(FILEINFO_MIME_TYPE);
   
   // Check the MIME type of a file
   $file = '/PHP/PhpProjects/myfile.txt';
   $fileType = $finfo->file($file);
   
   echo 'The MIME type of ' . $file . ' is: ' . $fileType;
?>

輸出

以下是以下程式碼的結果:

The MIME type of /PHP/PhpProjects/myfile.txt is: text/plain

示例 2

現在我們將使用 construct() 函式並建立 FileInfo 物件以獲取檔案的 MIME 編碼。

<?php
   // Create a new FileInfo object 
   $finfo = new finfo(FILEINFO_MIME_ENCODING);
   
   // Check the MIME encoding of a file
   $file = 'example.txt';
   $fileEncoding = $finfo->file($file);
   
   echo 'The MIME encoding of ' . $file . ' is: ' . $fileEncoding;
?> 

輸出

這將生成以下輸出:

The MIME encoding of /PHP/PhpProjects/myfile.txt is: us-ascii

示例 3

現在,以下程式碼使用自定義 magic 檔案建立新的 FileInfo 物件。

<?php
   // Path to a custom magic file
   $magicFile = '/path/to/custom/magic/file';
   
   // Create a new FileInfo object 
   $finfo = new finfo(FILEINFO_NONE, $magicFile);
   
   // Check the type of a file 
   $file = '/PHP/PhpProjects/myfile.txt';
   $fileInfo = $finfo->file($file);
   
   echo 'File info for ' . $file . ' using custom magic file: ' . $fileInfo;
?> 

輸出

這將建立以下輸出:

File info for /PHP/PhpProjects/myfile.txt using custom magic file: ASCII text

示例 4

在以下示例中,我們使用 construct() 函式建立 FileInfo 物件並獲取檔案型別。

<?php
   // Create a new FileInfo object
   $finfo = new finfo();
   
   // Check the file type of a file
   $file = '/PHP/PhpProjects/sample.txt';
   $fileInfo = $finfo->file($file);
   
   echo 'File info for ' . $file . ' is: ' . $fileInfo;   
?> 

輸出

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

File info for /PHP/PhpProjects/sample.txt is: ASCII text

總結

以上示例展示了使用 FileInfo 類的 __construct 函式檢索各種檔案相關資訊的多種方法。

php_function_reference.htm
廣告