1

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.

2
  • 3
    Class constants aren't global variables. The correct syntax is self::ITEMS_PER_STACK Commented Apr 28, 2022 at 22:36
  • 1
    Read php.net/manual/en/language.oop5.constants.php Commented Apr 28, 2022 at 22:37

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Did not know yet there is a difference. So thanks a lot for the quick and great answer :-) Upvoted
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.