簡體   English   中英

查看主PHP文件中包含文件的PHP變量

[英]Viewing PHP variables of an Included file in the main PHP file

我有一個PHP文件“ main.php”,該文件的頂部帶有以下語句:

include "config_file.php";

config_file.php包含五個簡單變量的設置。 有沒有一種方法可以顯示或查看main.php文件中的這五個變量? 如果不是,是否有更好的方法在main.php文件之外(在配置文件中)定義這些變量,而又在main.php文件中看到這些變量? 一個例子會有所幫助。

謝謝,Menachem

您可以直接使用包含文件的變量

只是

echo $var;

index.php

include 'config_file.php';
if(isset($db))
    echo 'set';
else
    echo 'not set'; // this will be called

config_file.php

$db = new mysqli("HOST", "USERNAME", "PASSWORD", "DB");

以及如何從包含的頁面訪問變量的 可能重復項

編輯01

a.php

$a = 'Abulla';
$b = 'Menachem';

b.php

你可以用

include 'a.php';
echo $a.' and '.$b;

通常,包括PHP文件將使您可以訪問此文件中定義的所有變量。 這意味着您可以只使用main.phpconfig_file.php中定義的變量。

例:

Main.php:

 <?php
    include "config_file.php";
    // The code included below is example, you may do anything you want with variables
    $example_result = $a + $b;
print($example_result); // Just and example
    file_put_contents ("debug.txt" , $example_result); // Just an example
    // This should result in debug.txt contain $a + $b meaning that this file content should be "3"

config_file.php:

   <?php
 $a = 1;
 $b = 2;

如果您的文件之一是PHP類,則這可能會略有不同。 在這種情況下,請給我們通知。

我想要查看源代碼中的“ include”文件變量的原因是為了提高代碼的可讀性。

我通過將“ include”文件的內容作為注釋粘貼到主文件中解決了這個問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM