JasonDavis
JasonDavis

Reputation: 48963

Easiest way to set a PHP CONSTANT in 1 file and access it everywhere?

I have asked similar questions before but here is a full demo example code. In PHP how can I access a Constant value that is set in a config file and then included into every page, Including CLASS FILES?

I realize this is some sort of scope issue so what is the best way to access this constant inside my class file below without passing the constant into the object when it ius created?

Right now, my class file thinks that the CoONSTANT DEBUG var is set to true even when it is false. True or false it still shows and I need to make it only work when the constant is set to true, any ideas?

Example config file that sets the constant value

<?PHP
//config.inc.php  
define('DEBUG', false);

echo 'config file loaded <br /><br />';

// load class file here
include 'some_class.php';
?>

Our class file that tries to access out Constant set in the config file above

<?PHP
//some_class.php

class Test{

    public function __construct()
    {
        echo 'some_class has been ran <br /><br />';

        if ( defined( 'DEBUG' ) )
        {
            echo 'DEBUG Constant is vissible inside our class file now!!!!! <br /><br />';
        }
    }

}
?>

Our test page which puts it all together

<?PHP
//any-file.php

include 'config.inc.php';

if(DEBUG){
    echo 'DEBUG Constant is vissible inside our Regular file, this is normal and always happens without any trouble though <br /><br />';
}

$test = new Test;
?>

Upvotes: 2

Views: 2370

Answers (3)

poke
poke

Reputation: 388023

Use defined to check if the constant was defined, instead of accessing its value:

if ( defined( 'DEBUG' ) )
{
    // debug commands here
}

And to disable the debug mode, simply uncomment the define line, so the constant is undefined again.

Upvotes: 1

Vince Bowdren
Vince Bowdren

Reputation: 9208

Define a function in an include file which returns the value of your constant?

Upvotes: 0

Andrew Noyes
Andrew Noyes

Reputation: 5298

Most frameworks accomplish this by being the central point of control for the entire website. If your web application isn't centralized, then you won't have a centralized configuration file, and won't have centralized access to the configuration.

When you define something using the define() function, it is defined in the global namespace, so any PHP files included from that point on will have access to it. This isn't the greatest situation, since predicates all code that depends on that constant on being included after the define() statement is run.

Upvotes: 0

Related Questions