未能在PHP中包含文件
我知道有很多与此相关的问题,我尝试了针对我的情况的解决方案,但没有一个奏效。 我必须修改使用FlightPHP框架(已经编写)构建的API。有100多个函数,其中大多数使用一些静态变量。我试图在一个页面中声明它们,这样如果有一天它们的值需要更改,我就可以通过在一个地方更改来轻松地完成 这是目录结构未能在PHP中包含文件,php,include,require,php-include,Php,Include,Require,Php Include,我知道有很多与此相关的问题,我尝试了针对我的情况的解决方案,但没有一个奏效。 我必须修改使用FlightPHP框架(已经编写)构建的API。有100多个函数,其中大多数使用一些静态变量。我试图在一个页面中声明它们,这样如果有一天它们的值需要更改,我就可以通过在一个地方更改来轻松地完成 这是目录结构 index.php constants.php FOLDER - firstInnerPage.php - secondInnerPage.php 我将展示每一页的样本 constants.
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';
?>
<?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;
}
?>
<?php
function firstInnerPageFunction()
{
require_once 'constants.php';
//require_once '../constants.php';
$avatar = $member_default_avatar;
}
?>
<?php
require_once('../constants.inc');
function firstInnerPageFunction()
{
global $myStaticVars;
extract($myStaticVars); // make static vars local
$avatar = $member_default_avatar;
}
第二个内页也是类似的,所以,我不包括在这里
我尝试以两种方式包含该文件:
1) require_once'constants.php'代码>
2) require_once'../constants.php'代码>
但两者都失败了。我要么得到一个包含文件失败的错误,要么未定义
变量$member\u default\u avatar
错误
有人能告诉我在这种情况下包含文件的正确方法是什么吗?谢谢大家。正如我在评论中所说,我不喜欢在函数中包含php文件。PHP文件应该始终具有全局作用域(除非您使用名称空间),尽量保持这样的简单
下面是一个代码示例:
contants.inc
<?php
$myStaticVars = ['member_default_cover' => 'img/members/member-default.jpg',
'member_default_avatar' => 'img/members/member-default.jpg'];
我认为需要_一次('../constants.php')
应该可以工作,但只有当constants.php
工作正常时。除此之外,我不会在一个函数中包含另一个php文件,它看起来就是不对。使用OOP(对象)隔离变量,或者将静态变量放入数组中,并在函数中使用global
来访问该数组。您正在将常量包括在该函数中,还包括indexPageFunction()您是否将其更改为require'../constants.php'No..in indexPageFunction(),我将其用作require_once'constants.php';并在内部页面中显示为require_once'../constants.php'@v SugumarI无法对代码进行太多更改,因为它已经在运行,我只是做了一些修改@KIKO软件我认为真正的阿米莉亚会比这更冒险。:-)