Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I see a variable defined in another php-file?

I use the same constant in all my php files. I do not want to assign the value of this variable in all my files. So, I wanted to create one "parameters.php" file and to do the assignment there. Then in all other files I include the "parameters.php" and use variables defined in the "parameters.php".

It was the idea but it does not work. I also tried to make the variable global. It also does not work. Is there a way to do what I want? Or may be there some alternative approach?

like image 407
Roman Avatar asked Jan 20 '26 00:01

Roman


2 Answers

I'm guessing you're trying to use the global variables within a function body. Variables defined in this fashion are not accessible within functions without a global declaration in the function.

For example:

$foo = 'bar';

function printFoo() {
  echo "Foo is '$foo'";   //prints: Foo is '', gives warning about undefined variable
}

There are two alternatives:

function printFoo() {
  global $foo;
  echo "Foo is '$foo'";   //prints: Foo is 'bar'
}

OR:

function printFoo() {
  echo "Foo is '" . $GLOBALS['foo'] . "'";   //prints: Foo is 'bar'
}

The other option, as Finbarr mentions, is to define a constant:

define('FOO', 'bar');

function printFoo() {
  echo "Foo is '" . FOO . "'";   //prints: Foo is 'bar'
}

Defining has the advantage that the constant can't be later overwritten.

like image 176
Kip Avatar answered Jan 21 '26 15:01

Kip


See PHP define: http://php.net/manual/en/function.define.php

define("CONSTANT_NAME", "Constant value");

Accessed elsewhere in code with CONSTANT_NAME. If the values are constant, you are definitely best to use the define function rather than just variables - this will ensure you do not accidentally overwrite your variable constants.

like image 23
Finbarr Avatar answered Jan 21 '26 17:01

Finbarr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!