PHP 7.2-包含文件无法访问另一个包含文件

时间:2019-11-09 01:23:07

标签: php include

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

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

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函数。 / include文件夹中还有其他文件,可以使用相同的include函数访问conn.php文件。

1 个答案:

答案 0 :(得分:0)

此问题与所谓的variable scopehttps://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
}