1

I need to change a global variable inside a namespace in PHP.

I'm currently refactoring some legacy code and a section of the code relies on the use of a global variable, which used to be configured in the code I'm refactoring.

I'm now trying to use namespaces on the new refactored code and can access the variable just fine by using \, but I couldn't find a way to change its value.

Sadly, changing the \legacyCode so it doesn't use the global variable is out of question.

Is not using namespaces here the only good solution?

Example:

namespace Namespace;

$GlobalVariable = 123;

abstract class NamespaceClass extends \legacyCode
{
} 
// no namespace defined

class legacyCode
{
    function doSomething() {
        global $GlobalVariable;

        echo $GlobalVariable;
        // GlobalVariable is undefined
    }
}

Thanks in advance.

  • Are you sure that what you are talking about is variable? Namespaces in php only affects classes, functions and constants, not variables. – Michal Hynčica Sep 09 '19 at 21:43
  • 2
    `legacyCode` is a class , it has no global variables, do you mean change a property of the parent class `legacyCode` inside the child class `NamespaceClass`? **please show the code that failed** – Accountant م Sep 09 '19 at 21:54
  • @Accountantم With legacyCode I meant the class that doesn't have a namespace and contains the global variable $GlobalVariable, when I try to change its value inside NamespaceClass it only affects the namespace of the NamespaceClass. I will try to improve the code example. – Matheus Patrick Sep 10 '19 at 11:27
  • 1
    You need to include or require the first file before using it's global variables, in the second file do `require_once 'path/to/firstFile.php';` – Accountant م Sep 10 '19 at 12:16
  • I think that was the issue thank you! I actually did use require_once on the file but in a way that wouldn't work with global variables. Cheers! – Matheus Patrick Sep 10 '19 at 16:47

0 Answers0