【问题标题】:Defining constants in index file在索引文件中定义常量
【发布时间】:2016-11-06 18:50:05
【问题描述】:

我的应用程序通过索引文件路由每个请求。这个文件有

require_once $_SERVER['DOCUMENT_ROOT'] . "/app/config/config.php"

此配置文件定义了路径常量,因此它们可以在其他地方使用,但它似乎不起作用。例如在 config.php 我有

define('MODELS', $_SERVER['DOCUMENT_ROOT'] . "/app/models/");

在其中一个模型文件中,我试图包含另一个类,例如

require_once MODELS . "classA.php"

class classB {.....}

我收到未定义常量模型的错误。任何想法如何解决这一问题?理想情况下,我希望可以从我的应用程序中的任何位置访问这些常量。

config.php:

$root = $_SERVER['DOCUMENT_ROOT'] . "/";
define("APP",$root . "app/"); // app folder
define("CONFIG",$root . "app/config/"); // config folder
define("MODELS",$root . "app/models/"); // models folder
define("CONTROLLERS",$root . "app/controllers/"); // controllers folder
define("DB",$root . "app/db/"); // database connection folder
define("VIEWS",$root . "app/views/"); // views folder
define("FUNCTIONS",$root . "app/functions/"); // functions folder
define("LIBRARY",$root . "app/library/"); // library folder
define("PUBLIC",$root . "public/"); // public folder

index.php:

require_once $_SERVER['DOCUMENT_ROOT'] . "/app/db/dbconnect.php";
require_once $_SERVER['DOCUMENT_ROOT'] . "/app/config/config.php";
require_once FUNCTIONS . "clean.php";
require_once MODELS . "core.php";
require_once MODELS . "user.php";
require_once MODELS . "browser.php";
require_once MODELS . "call.php";
require_once MODELS . "module.php";

错误来自某个文件:

if(isset($_POST['submit']) && $_POST['submit'] == "Send")
{
require_once MODELS . "contact.php";
$contact = new contact();
}

【问题讨论】:

  • define('MODELS', $value)
  • @u_mulder 抱歉,这是一个错字,我的实际代码确实包含引号
  • 要么你命名常量错误,要么你的配置文件没有包含。
  • @u_mulder,但我在索引文件中进一步使用常量,它们工作正常吗?
  • 您确定在some file 中包含config.php

标签: php scope constants


【解决方案1】:

快速修复但坏主意:

将您的 index.php 文件与 PHP 神奇常量 __DIR__ 一起用作全局参考点。

index.php

require_once __DIR__."/config.php"; // This loads your constants

config.php

define('PATH', __DIR__."/any_folder_you_want"); // Repeat this for your folders

做对了:

一般来说,您不希望以这种方式组织您的项目,因为这可能会在未来导致重大的架构问题。

解决方案:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-31
    • 1970-01-01
    • 1970-01-01
    • 2014-05-14
    • 1970-01-01
    • 1970-01-01
    • 2016-09-14
    • 1970-01-01
    相关资源
    最近更新 更多