When I was learning javascript, the global variable issue was emphasized by book or tech article authors, a.k.a one should always try to avoid using global variables. One of the reasons I believe is to avoid naming conflict. And I think no matter what language we are using, naming conflict will always be an issue.
However, when I read PHP books, using of global variable is not perticularly mentioned or marked as bad practice. So shall I pay attention to it?
For example, I am trying to modify some PHP file in Joomla. if I write a custom function getJson()
in a template file of a module, how do I know the function name is not being used somewhere by other components?
Your first question is about a variables the second about function names.
Is using of global variables bad pratice?
Yes, if you are using too many variables and lose the overview about the useage! Think about a coder team with 20 coder on one big project with 1000+ files.
No, if you use globals wisly. Like the most Framework do.
Topic: TO OOP OR NOT TO OOP (Object-oriented programming)
So shall I pay attention to it?
In your case, using Joomla, you should take a look how and for what Joomla is using global vars. And use them in that way too.
In your other projects, give them an custom useage,like: global vars only for class instances.
Its all about how you code, more OOP or more PROCEDUAL or all mixed up .... php is a big open world.
how do I know the function name is not being used somewhere by other components? function_exists('getJson'); ;)
Whatever, for this problem php has namespaces.
namespace MySpace {
function getJson(){}
}
use MySpace\getJson as getJson;
getJson($args);
You should read a little about it.
if I write a custom function getJson() in a template file
You can do with a anonymous function:
$getJson = function(){};
instead of creating a global function. If the function is only used in this template!
Hope that helps a little.
Investigation is key in your situation.
Make sure error_reporting(E_ALL);
is set in your development environment.
Before creating the function, run a recursive search through all of your PHP files for some combination of function getJson(
I am not familiar with Joomla but if namespacing is being used then you may run into false-positives.
If namespacing is being used then make sure to not run into namespacing conflicts by referring to first point - error_reporting(E_ALL);
Use namespaces like a boss (requires PHP 5.3.0 or later):
namespace NameSpaceThatIsDefinitelyNotUsedanywhereksdgbdihjfgbdfbgd{ function getJson(){} } use NameSpaceThatIsDefinitelyNotUsedanywhereksdgbdihjfgbdfbgd\getJson as getJson; getJson($args);
Instructions for #2
function getJson(