在 PHP 中包含文件失败

Failure in including files in PHP

我知道有很多与此相关的问题,我尝试了适合我的情况的解决方案,但 none 的解决方案有效。 我必须修改使用 FlightPHP 框架(已编写)构建的 API。有 100 多个函数,其中大部分使用一些静态变量。我试图在单个页面中声明它们,这样如果有一天它们的值需要更改,我可以通过仅在一个地方更改它来轻松完成。

这是目录结构。

index.php
constants.php
FOLDER
  - firstInnerPage.php
  - secondInnerPage.php

我将展示每页的样本。

constants.php

<?php
$member_default_cover  ='img/members/member-default.jpg';
$member_default_avatar ='img/members/member-default.jpg';
?>

这些是我想在每个函数中使用的常量。

index.php

<?php
require 'flight/Flight.php';

//Route to index page function
Flight::route('/indexPageFunction', function()
{
   pages_included();    
   $returnarray=indexPageFunction();
   header('Content-type:application/json;charset=utf-8');
   echo json_encode($returnarray);
});

//Route to first page function
Flight::route('/firstInnerPageFunction', function()
{
   pages_included();    
   $returnarray=firstInnerPageFunction();
   header('Content-type:application/json;charset=utf-8');
   echo json_encode($returnarray);
});

//Route to second page function
Flight::route('/secondInnerPageFunction', function()
{
   pages_included();    
   $returnarray=secondInnerPage();
   header('Content-type:application/json;charset=utf-8');
   echo json_encode($returnarray);
});

Flight::start();

//Calling this function includes the inner page and makes them accessible
function pages_included()
{   
  require_once 'FOLDER/firstInnerPage.php'; 
  require_once 'FOLDER/secondInnerPage.php'; 
}

//Index page function
function indexPageFunction()
{
 require_once 'constants.php';
 $avatar =  $member_default_avatar;
}

?>

对于索引页功能,文件被包含在内。当用户发出请求时,它首先到达请求被重定向到正确功能的路由。但是内页有自己的功能。它们被写在单独的页面中以对功能进行分类。这些页面包含在路由本身中,因此当对内页功能的请求到来时,这些文件将被包含在内。 pages_included() 完成包含内页的工作。

这是内页的样子。

firstInnerPage.php

<?php
function firstInnerPageFunction()
{
 require_once 'constants.php';
 //require_once '../constants.php';
 $avatar = $member_default_avatar;
}
?>

第二个内页也类似,所以这里就不放了。

我尝试以两种方式包含文件: 1) require_once 'constants.php'; 2) require_once '../constants.php';

但都失败了。我得到一个 failed to include the file 错误或 undefined 变量 $member_default_avatar 错误。

谁能告诉我在这种情况下包含文件的正确方法是什么?谢谢大家

正如我在评论中所说,我不喜欢在函数中包含 php 文件。 PHP 文件应始终具有全局范围(除非您使用名称空间),尽量保持简单。

所以,这是一个代码示例:

contants.inc

<?php

$myStaticVars = ['member_default_cover'  => 'img/members/member-default.jpg',
                 'member_default_avatar' => 'img/members/member-default.jpg'];

firstInnerPage.php

<?php

require_once('../constants.inc');

function firstInnerPageFunction()
{
  global $myStaticVars;
  extract($myStaticVars);  // make static vars local
  $avatar = $member_default_avatar;
}

这样你也可以确保静态变量总是可用的,因为如果你在不同的函数调用中对同一个文件使用 require_once 它只会对你调用的第一个函数有效。

如果您的静态变量确实是常量,您也可以使用 define() 而不是数组。好处是常量随处可用,在函数内部也是如此。