views:

103

answers:

4

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?

+2  A: 

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.

Finbarr
Most naming conventions would argue against using dashes in constant/variable names - use an underscore instead.
adam
This is certainly true for PHP.
Finbarr
A: 

Have all your pages start in the one file that defines the parameters and then dispatch to the respective sub pages. This way the variables defined in first file will exist in all included pages.

unholysampler
That's not a better way, it's just an alternative - and it offers no fix.
adam
+2  A: 

That is exactly how it works.

Have you got error reporting set up, and is there anything in the error log? I'm guessing the include is failing but you're not seeing the error.

adam
Thank you. Now it works. I had an inconsistency in names (spell mistake).
Roman
A: 

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.

Kip