2

I looked into past answers and was led to believe PHP variables assigned in a header file are global. I must be doing something wrong then. Here's a much-simplified version of my code:

This is my myGlobals.php file:

<?php

  $NAMELABEL = "Name";

?>

This is file index.php that 'requires' myGlobals.php then calls a function in a 3rd php file

<?php

   require_once 'myGlobals.php';
   require_once 'DisplayRecords.php'; 

   displayRecords(); 
?>

And here is DisplayRecords.php

<?php

  function displayRecords()
 {
    echo '<table border="1">';
    echo '<tr>';
    echo '<th>' . $NAMELABEL . '</th>';
    echo '</tr>';
    echo "</table>";
  }
?>

This is HIGHLY simplified, only the code causing the error.

The error msg. I get when I run it is:

Notice: Undefined variable: NAMELABEL in C:\xampp\htdocs\fbreverse\DisplayRecords.php on line 29

Now, before I changed to the global variable $NAMELABEL -- I used this and it worked fine:

   echo '<th>Name</th>';

by 'fine' I mean that the table was created and it had a header called Name as on of the columns.

NOTE: using single quotes around the html tags above is allowed, and needed if you use a double-quoted string in the tag, as I did in echo '<table border="1">' -- so I just stayed consisted and stuck with the single quote. Changing the above example to

 echo "<th>" . $NAMELABEL . "</th>";

made zero difference, same error message, Notice: Undefined variable: NAMELABEL in C:\xampp\ht........blah blah

Why isn't $NAMELABEL visible in the function displayRecords() inside DisplayRecords.php?

1
  • You should look into one of the common templating engines anyway. Typically such output variables are collected in an array or object, and then simply localized in the template file or functions using extract (or not). While the globals bickering is redundant as usual, it's very obviously the least suitable approach for output variables. (Your example is too terse, not sure about constants.) Commented Jun 9, 2011 at 2:10

4 Answers 4

4

You need to add at the top of your function...

global $NAMELABEL;

This will make $NAMELABEL available inside of your function.

Globals however should be minimised. Could you re-factor your code?

Sign up to request clarification or add additional context in comments.

7 Comments

So -- implicitly it sounds like part of the answer is 'yes they're global but only for inline code -- when you try to access a variable in a function, it has to: (1) be assigned first inside that function before being used, or (2) be prepended with 'global' so the function knows to resolve that variable name outside the scope of the function -- Correct?
Eh, sort of. include and require are treated like you copy+pasted the code into the script. They're not a special type of variables, they're just normal variables.
@wantTheBest Yes, but assigned first will declare a local to the function.
My objective is to create some named values that will be used throughout several different PHP files -- in C or C++, I would use a header file with this -> #define NAMELABEL "Name" and then I could use NAMELABEL in any file just by includ'ing the header file -- that's what I need to do here -- is there a way to do it in php?
@wantTheBest I'm not sure, I have not used C in a while.
|
4

I looked into past answers and was led to believe PHP variables assigned in a header file are global.

Not within functions, they're not, unless you specifically tell the function to treat it as global.

function myFunction() {
  global $myVariable;
}

See http://php.net/manual/en/language.variables.scope.php for more details on variable scope in PHP.

As a side note, the way you're using this appears better suited to constants, which won't need to be declared as global - they are always global.

Comments

2

Because of variables scope. If you need to pass something into the function - use function arguments.

And no - global in other answers is never a good idea.

5 Comments

@ceejayoz: It is the classical case when never is suitable to use. Otherwise - give an example when global is better (don't forget about OOAD and best programming practices)
Not everyone's using OOP. Even with OOP there are legit arguments that globals can be better in some apps than some sort of registry class to pass globally required stuff like database instances around.
@ceejayoz: sure, but registry can help you to handle dependencies, while global cannot. With globals you loose the program flow.
@zerkms: you can overload the $GLOBALS array. Comes pretty close to some registry. But that's not promoting the use of global in functions. It should be prevented and existing code refactored that it doesn't need it any longer to make application code more fluid and ready for future developments.
I usually start with globals and maybe -- just maybe -- end up creating some sort of registry class -- but this is not always the case
2

Because a variable is declared in the global scope doesn't mean it is accessible everywhere. Variables are not handled the same way as Javascript does. However, using classes and OO paradigms, the variables declared inside classes behave the same as in other languages (ie. Java, C#, etc.). This is a vestige of earlier versions of PHP.

So, if $NAMELABEL is a constant (non changing variable), a solution could be to use define() instead.

define('NAMELABEL', 'Name');

and use it anywhere in your code :

function displayRecords()
{
   echo '<table border="1">';
   echo '<tr>';
   echo '<th>' . NAMELABEL . '</th>';
   echo '</tr>';
   echo "</table>";
}

But yet a better idea would be to create a class and store the values therein. For example :

class Labels {
    static public $NAME = "Name";
}

and use it like this

function displayRecords()
{
   echo '<table border="1">';
   echo '<tr>';
   echo '<th>' . Labels::$NAME . '</th>';
   echo '</tr>';
   echo "</table>";
}

6 Comments

Got it -- looks like PHP has an analog to #define used in C++ -- this 'define(..)' is similar in name, different in syntax, but seemingly identical in effect -- I'm using it man -- thanks!
just a word of best practices, do not over use define. The second idea is much better, as it keeps your "constants", or however you use the values, in a separate context.
I like the class idea. Truth be told I would have done that myself in Java or C++ too. I was not aware that class was available in PHP -- kinda of new to php -- but 11 years back, the last time I wrote code in industry, I would have looked for that first as in a code review it will most assuredly be respected, and the usage back in the 90s was standard. I fooled myself into thinking I'd remember everything. I'm resetting my expectations on my recall capability, bummer that. Not like hopping on a bicycle again after a 10-year hiatus.
yes, IT/programming is one of those fields that, even 1 year away from it, you can easily get lost and forget everything... Ten years ago, I did a lot of VB, but now I look at the language (even my old VB6 projects) and I'm a bit confused! The good part of it, though, is that once you learned it, it can easily be picked up. Not like riding a bicycle, but more like driving a car, or a big truck :)
@Yanick: "The second idea [of static vars in a class] is much better [to keep things] in a separate context" -- but what about namespacing the constants? Since php now supports namespaces...
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.