jmng
jmng

Reputation: 2568

Define PHP constant only once

I'm using php.ini (on nginx) to store database access credentials for PHP, aiming to get this data out of .php files.

I'd like to set global constants with these values once (only) and make them accessible to all scripts.

I'm currently doing as shown below, this script is require_once() by the database interface script. It works, but on the next request or whenever a page calls the dbinterface script, the constants have to be defined again, possibly because of a scope issue (from what I can gather).

Is there some way, other than using APC, to define these just once?

<?php
    if( !configLoaded() )
        loadConfig();


    function loadConfig()
    {
        $vars = array("A","B","C");

        foreach( $vars as $v )  
           define( $v, get_cfg_var( "ubaza.cfg.$v" ) );
    }


    function configLoaded() //returns false as soon as the caller script exits
    {
        return defined("A") && defined("B") && defined("C");
    }
?>

Upvotes: 2

Views: 3803

Answers (3)

Eoin Murphy
Eoin Murphy

Reputation: 813

What about using auto_prepend_file to run your script before running anything else?

https://www.php.net/manual/en/ini.core.php#ini.auto-prepend-file

That way you could write your script once, and then, when set, it will define all constants at the start of runtime.

Upvotes: 1

Lupin
Lupin

Reputation: 1244

You can also set a variable in htaccess and get it in PHP

SetEnv YOURVAR value

And get it in PHP:

print $_SERVER["YOURVAR"];

However as you want to have the constants with values from php.ini - not sure you are able to set them in the htaccess from php.ini

Upvotes: 5

rm-vanda
rm-vanda

Reputation: 3158

Constants have to be "re"-defined every time a script is run because when the script is done, garbage collection cleans it up.

If you need to ensure the constants are only defined once per script, you are doing it correctly -- the current method is perfectly acceptable.

However, if you want to define the constants once and never worry about them again, ever - look into hidef.

It allows allows you to put your constants in an .ini file, thus they are already defined before any script is executed. Coincidentally, it is also the fastest way of using constants, although it takes a bit more RAM.

Upvotes: 1

Related Questions