'Global php variable is always null

I have a bug in my application which I do not understand at all. I made a minimal example which reproduces the issue:

<?php
class MyClass {

  const ITEMS_PER_STACK = 30;

  public function test(): int {
    global $ITEMS_PER_STACK;
    return $ITEMS_PER_STACK;
  }
}

$a = new MyClass();
echo($a->test());

Expected behavior is an output of 30 while in reality if throws a null exception because the global variable cannot be accessed. Can someone explain it to me why this happens and how to fix this? Would be much appreciated, thanks.

php


Solution 1:[1]

If ITEMS_PER_STACK is declared the way you indicate, the way to refer to it from inside the class is with self::ITEMS_PER_STACK.

So:

<?php
class MyClass {

    const ITEMS_PER_STACK = 30;

    public function test(): int {
        return self::ITEMS_PER_STACK;
    }
}

$a = new MyClass();
echo($a->test());

See: Class Constants

You would use the global keyword to force usage of a variable declared somewhere outside the class, like this:

<?php

$outside_variable = 999;

class MyClass {

    const ITEMS_PER_STACK = 30;

    public function test(): int {
        return self::ITEMS_PER_STACK;
    }

    public function testGlobal(): int {
        global $outside_variable;
        return $outside_variable;
    }
}

$a = new MyClass();
echo($a->testGlobal());

See: Global Scope in PHP

Solution 2:[2]

While the above answer does tell you the solution, it is not the proper way to do this.

Using globals is highly discouraged and leads to numerous bugs and oddities in your applications.

Your initial approach to use a constant is correct, however you need to call it by referencing the class in which it resides if it's not in the same class (where you use self::ITEMS_PER_STACK) as per the above answer.

If you want to use this constant in another class simply prefix it the name of the class in which it resides.

<?php
class MyClass {

    const ITEMS_PER_STACK = 30;

}

echo MyClass::ITEMS_PER_STACK;

Also note that from PHP 7.1 you can add the visibility of the constant such as:

public const ITEMS_PER_STACK = 30;

See Example #4 https://www.php.net/manual/en/language.oop5.constants.php

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 ikyuchukov