Page 1 of 1

Why global constants aren't accessible within classes?

Posted: Tue Dec 01, 2009 4:14 pm
by polk
Hello!

Do you know by any chance how could I access a global constant from a class?

for example:

Code: Select all

<?php
 
define('MY_CONSTANT', 'Hello World');
 
// MY_CONSTANT will be accessible from any function but not from classes, why? How can I solve this?
 
function myFunction()
{
    echo MY_CONSTANT; // print "Hello World"
}
 
class myClass 
{
    const MY_CLASS_CONSTANT = "Grrrrr";
 
    public function __construct()
    {
        echo MY_CONSTANT; // error...
        echo MY_CLASS_CONSTANT; // print "Grrrrr"
    }
}
?>
 
Any idea?
How can I access MY_CONSTANT without passing it to the constructor with something like myClass(MY_CONSTANT);........ ??

Thanks a lot :wink:

Re: Why global constants aren't accessible within classes?

Posted: Tue Dec 01, 2009 4:28 pm
by AlanG
What's version of PHP are you using? I have tested your code and it works. There is a warning though (details below).

Code: Select all

class myClass
{
    const MY_CLASS_CONSTANT = "Grrrrr";
 
    public function __construct()
    {
        echo MY_CONSTANT; // error...
        [color=#FF0000]echo MY_CLASS_CONSTANT;[/color] // This needs to be referenced like: self::MY_CLASS_CONSTANT;
    }
}
Constants are implicitly global. Variables are a different story. You need to specify them as a global variable using the global keyword or accessing the Globals array directly.

e.g.

Code: Select all

$myVar = "My Variable";
 
// MY_CONSTANT will be accessible from any function but not from classes, why? How can I solve this?
 
function myFunction()
{
    $myVar = true; // Completely different variable to the one defined in the global scope
 
    global $myVar;
    // ... or ...
    $myVar = $GLOBALS['myVar'];
}
 

Re: Why global constants aren't accessible within classes?

Posted: Tue Dec 01, 2009 4:43 pm
by polk
Yes sorry I forgot the "self::" for MY_CLASS_CONSTANT..

I'm using PHP 5.3


heeeeeeeee!!!!! it works!! :crazy: Sorry I didn't sleep last night and I don't know what I was thinking when I saw self::MY_CONSTANT :lol: removed the self:: and it works great.

It's because I'm switching some constants from local class constants to global constants and I completely forgot to remove this self thing..

anyway thanks a lot, solved!

Re: Why global constants aren't accessible within classes?

Posted: Tue Dec 01, 2009 4:47 pm
by AlanG
polk wrote:heeeeeeeee!!!!! it works!! :crazy: Sorry I didn't sleep last night and I don't know what I was thinking when I saw self::MY_CONSTANT :lol: removed the self:: and it works great.
lol no worries. Been in that boat myself a few times. I don't blame caffeine though, blame the PS3! =P