1

I'm starting with OOP in PHP and I have an issue with global variables.

Example of my current structure:

test.php REQUIRES globals.php and also INCLUDES classes.php.


globals.php has this code:

global $something;
$something = "my text";

and classes.php looks like this:

global $something;

class myClass {
    public $abc = "123";
    public $something;

    public function doSomething() {   
        echo $this->abc."<br>";
        echo $this->something;
    }
}

$class = new myClass();
$class_Function = $class->doSomething();

print_r($class_Function);

At the end, test.php only shows "123".

I tried using "include()" instead of "require" for globals.php but didn't work. Neither did including globals.php in classes.php.

Jimmy Adaro
  • 1,325
  • 15
  • 26

1 Answers1

3

$this->something was never initialized. The global $something is totally outside of scope and is not related to the class attribute $this->something. If you need to access a global inside a function or method you need to declare it as global:

public function doSomething() {   
        global $something;
        echo $this->abc."<br>";
        echo $something;
    }

However you need to stop using globals because is not a good solution. If you need do define some constant values that are global to your system it's prefered to use define()

define("SOMETHING","My text")

And then you can access it in any part of your code:

echo SOMETHING;

Also see: PHP global variable scope inside a class and Use external variable inside PHP class

Community
  • 1
  • 1
F.Igor
  • 4,119
  • 1
  • 18
  • 26
  • Thanks for your response. How can I access to `SOMETHING` in the class? `public SOMETHING;` throws this error: `Parse error: syntax error, unexpected 'SOMETHING' (T_STRING), expecting variable (T_VARIABLE)` – Jimmy Adaro Mar 07 '17 at 19:59
  • For defines, you don't need to declare inside the function. Only use `echo SOMETHING;` (it Doesn't need `$`) – F.Igor Mar 07 '17 at 20:01
  • I get an approach using `public $something = SOMETHING;` – Jimmy Adaro Mar 07 '17 at 20:02
  • 1
    Yes, you can initialize an attribute using the define. – F.Igor Mar 07 '17 at 20:03