Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
PHP - Why using "global" considered bad?
In PHP why is using global
like in the example below considered bad?
$a = 1;
class foo
{
public function bar()
{
global $a; // <-- Why is this considered bad?
}
}
I want a concrete example(s) of what can go wrong with this code.
1 answer
The following users marked this post as Works for me:
User | Comment | Date |
---|---|---|
Vanity Slug ❤️ | (no comment) | May 13, 2024 at 14:50 |
Nothing in particular will go wrong. global
is a valid and supported keyword, the code will work. There is no problem for the computer.
The problem is for you. When something is global
, it could be getting changed by anything else. You have to read through the whole codebase, to understand what exactly it's used for. If it's local, then it cannot be changed by things outside the local scope, which makes it a lot easier for a human brain to keep track of things.
This is the main thing wrong with global
and it's not specific to PHP.
1 comment thread