PHP 7.2-包含文件无法访问另一个包含文件
我在一个包含文件访问另一个包含文件(我的数据库连接)时遇到问题 我有一个布局如下的站点:PHP 7.2-包含文件无法访问另一个包含文件,php,include,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
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);
?>
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文件 这个问题与称为
变量范围的东西有关
==>请阅读以获取详细信息
第二个例子描述了您的问题
func公司
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
<?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
}
<?php
function myFunc($conn){
echo $conn; //outputs $conn
}
<?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);
<?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
}