How to use DEFINE vars inside functions

81 views Asked by At

I have a pure PHP script - no frameworks, no OOP - like this:

<?php

define('VAR1', 'xxxxxxxxxx');
define('VAR2', 'xxxxxxxxxx');
define('VAR3', 'xxxxxxxxxx');

function myFunction()
{

    // I need to access VAR1, VAR2, VAR3 here

}

$output = myFunction();

How do I access VAR1,VAR2 and VAR3 inside myFunction()? By declaring them as GLOBAL inside the function?

2

There are 2 answers

1
Muhammet On BEST ANSWER

The scope of a constant is already global, so just use them as they are:

define('VAR1', 'xxxxxxxxxx');
define('VAR2', 'xxxxxxxxxx');
define('VAR3', 'xxxxxxxxxx');

function myFunction()
{
    echo VAR1;
    // I need to access VAR1, VAR2, VAR3 here

}

$output = myFunction();
0
Reeno On

According to http://php.net/manual/en/language.constants.php "the scope of a constant is global. You can access constants anywhere in your script without regard to scope."

So, it's really easy:

<?php

define('VAR1', 'xxxxxxxxxx');
define('VAR2', 'xxxxxxxxxx');
define('VAR3', 'xxxxxxxxxx');

function myFunction()
{
  echo VAR1;
  echo VAR2;
  echo VAR3;
}

$output = myFunction();