What is the best way to define a global constant in PHP which is available in all files?

48,017

Solution 1

Define your constant in your top .php file, that will be included in all the other scripts. It may be your front controller, your config file, or a file created for this single purpose.

!defined('MY_CONST') && define('MY_CONST', 'hello');

Solution 2

do the following:

define("CONSTANT_NAME","value");

if you want to access this constant from other php files, you have to include it:

include_once("thefilewiththeconstant.php");

Solution 3

check this

<?php
//Global scope variables
$a = 1;
$b = 2;

 function Sum()
 {
global $a, $b;

$b = $a + $b;
 } 

Sum();
echo $b;
?>

Solution 4

It depends. In your situation I would go for define() because it has a more compact syntax in usage. But define() can only hold scalar values in PHP < 7.0 In case you need i.e. an associative array you have no other choice then to go for $GLOBALS or use PHP >=7.0.

// Storing a single value works fine with define
define( 'ROOT_DIR', dirname(dirname(__FILE__)) . '/' );

// But not for complex data types like this array
$USERPIC_PARAMS = array(
            "user_root"       => "images/users",
            "padding_length"    => 8,
            "split_length"      => 4,
            "hash_length"         => 12,
            "hide_leftover"     => false
    );

// Then you need $GLOBALS
$GLOBALS['USERPIC_PARAMS']  = $USERPIC_PARAMS;
// Or in PHP >=7.0
define( 'USERPIC_PARAMS', $USERPIC_PARAMS );

// output your define
echo ROOT_DIR;
// output your $GLOBALS var
echo $GLOBALS['USERPIC_PARAMS'];
// output in PHP >=7.0 your constant
echo USERPIC_PARAMS;
Share:
48,017
cldy1020
Author by

cldy1020

Updated on July 22, 2022

Comments

  • cldy1020
    cldy1020 almost 2 years

    What is the best way to define a constant that is global, i.e., available in all PHP files?

    UPDATE: What are the differences between constants and class constants? Can they be used interchangeably?