首頁 >後端開發 >php教程 >版本更新後如何將變數傳遞給包含的 PHP 檔案?

版本更新後如何將變數傳遞給包含的 PHP 檔案?

DDD
DDD原創
2024-10-29 05:30:02462瀏覽

How to Pass Variables to Included PHP Files After a Version Update?

向包含的PHP 檔案傳遞變數

問題摘要

PHP 版本更新後,使用常用方法向包含的PHP 檔案傳遞變數會出現問題。該變量,特別是 $_SERVER['PHP_SELF'],需要在呼叫檔案中設定並由包含的檔案存取。

分析和解決方案

儘管普遍認為需要特定的概念將變數傳遞給包含文件的措施,PHP 的固有行為允許在包含語句之前聲明的變數在包含文件中可用。

重要說明:將變數傳遞給呼叫include 語句的函數

但是,將變數傳遞給內部使用include 語句的函數需要一種稱為extract()的技術。

使用 extract() 的方法

考慮以下程式碼片段:

<code class="php">function includeWithVariables($filePath, $variables = array(), $print = true)
{
    // Extract the variables to a local namespace
    extract($variables);

    // Start output buffering
    ob_start();

    // Include the template file
    include $filePath;

    // End buffering and return its contents
    $output = ob_get_clean();
    if (!$print) {
        return $output;
    }
    echo $output;
}</code>

此函數採用包含檔案路徑、可選變數陣列和列印標誌。

index.php:

以上是版本更新後如何將變數傳遞給包含的 PHP 檔案?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn