【问题标题】:PHP 7.2 - Include file cannot access another include filePHP 7.2 - 包含文件无法访问另一个包含文件
【发布时间】:2019-11-09 01:23:07
【问题描述】:

我遇到了一个包含文件访问另一个包含文件(我的数据库连接)的问题

我有一个具有以下布局的网站::

root/conn.php :: db connection file  
root/site/file1.php :: regular page  
root/site/include/func.inc :: file with functions in it

下面列出了每个文件以及相应的代码...

conn.php ::

<?php

$host = 'localhost';
$db   = 'mydb';
$user = 'myuser';
$pass = 'mypass';
$charset = 'utf8mb4';

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
    $conn = new mysqli($host, $user, $pass, $db);
    $conn->set_charset($charset);
} catch (\mysqli_sql_exception $e) {
     throw new \mysqli_sql_exception($e->getMessage(), $e->getCode());
}
unset($host, $db, $user, $pass, $charset);

?>

file1.php ::

include_once ("{$_SERVER['DOCUMENT_ROOT']}/conn.php");
include_once ("{$_SERVER['DOCUMENT_ROOT']}/site/include/func.inc");
{ code that calls functions in func.php }

func.inc ::

include_once ("{$_SERVER['DOCUMENT_ROOT']}/conn.php");
{ various functions }

当我浏览到 /file1.php 时,我收到以下错误 ::

PHP Notice:  Undefined variable: conn in C:\inetpub\root\site\include\func.inc on line 231
PHP Fatal error:  Uncaught Error: Call to a member function prepare() on null in C:\inetpub\root\site\include\func.inc:231

我的 func.inc 文件似乎找不到 conn.php 文件。我还尝试从 func.inc 中删除包含函数。 /include 文件夹中还有其他文件可以使用相同的包含功能访问 conn.php 文件。

【问题讨论】:

    标签: php include


    【解决方案1】:

    该问题与称为 variable scope (https://www.php.net/manual/en/language.variables.scope.php) 的东西有关 ==>请阅读以获取详细信息

    第二个例子描述了你的问题

    func.inc

    <?php
    include_once ("{$_SERVER['DOCUMENT_ROOT']}/conn.php");    
    // to illustrate the issue, the include can be simplified to 
    // $conn = "something";  // => global scope variable
    
    function myFunc(){
        echo $conn; //no output - $conn exists ONLY in the local scope --> not available inside thisfunction
    }
    

    解决方案 1:

    func.inc

    <?php
    function myFunc($conn){
        echo $conn; //outputs $conn
    }
    

    file1.php

    <?php
    include_once ("{$_SERVER['DOCUMENT_ROOT']}/conn.php");
    include_once ("{$_SERVER['DOCUMENT_ROOT']}/site/include/func.inc");
    
    //call function and pass the $conn, it's available here in the global scope
    myFunc($conn); 
    

    解决方案 2

    但请记住,global 被认为是不好的做法

    func.inc

    <?php
    include_once ("{$_SERVER['DOCUMENT_ROOT']}/conn.php");    
    
    function myFunc(){
        global $conn; //$conn is declared global in the local scope of this function
        echo $conn; //outputs $conn from conn.php if you call myFunc from anywhere
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-10
      • 2011-08-02
      相关资源
      最近更新 更多