Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading