Home > Software design >  Global php variable is always null
Global php variable is always null

Time:04-29

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.

CodePudding user response:

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

  • Related