Josh Jackson Josh Jackson - 2 months ago 26
PHP Question

Defining constants in index file

my application routes every request through an index file. This file has

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

This config file defines path constants so they can be used elsewhere, but it doesn't seem to work. For example in config.php I have

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

In one of the model files I am trying to include another class such as

require_once MODELS . "classA.php"

class classB {.....}

I get an error for undefined constant MODELS. Any ideas how to fix this? I would ideally like for these constants to be accessible from anywhere in my application.


$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


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";

error comes from some file:

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


Quick fix but bad idea:

Use your index.php file as global reference point together with the PHP magical constant __DIR__.


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


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

Doing it right:

Generally speaking, you don't want to organize your project that way since it might lead to major arquitectual problems in the future.