tags:

views:

76

answers:

3

Why doesn't this work?

define("STR_TEST", "qwerty");

class Test
{
    public $arrTest = array(
        "test"=>"Bla bla bla ".STR_TEST
    );
}

$objTest = new Test();

print($objTest->arrTest["test"]);
+5  A: 

You can only use simple values in a property declaration:

[The] declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

Especially the concatenation operator is not allowed at that point. If you want to initiate it with a value that is derived from other values, you need to do that in the constructor:

class Test {
    public $arrTest;

    public function __construct() {
        $this->arrTest = array(
            "test" => "Bla bla bla ".STR_TEST
        );
    }
}
Gumbo
+8  A: 

You can perfectly use constants in class member declarations

define('SOME', 12345);

class A {
    public $x = SOME; // works
}

$o = new A;
echo $o->x; 

The problem is that member declarations do not allow expressions of any kind:

class B {
    public $x = 1 + 1; // no
    public $y = foo(); // no
    public $z = CONST . CONST; // no
}

Note that this limitation is purely syntactical, that is, the php parser, for whatever reason, simply does not accept expressions there. It's quite possible to have runtime-dependent code in member declarations:

define('IP', $_SERVER['REMOTE_ADDR']);

class B {
    public $ip = IP;
}

$o = new B;
echo $o->ip;

That is, the documentation quoted above is wrong at this point.

stereofrog
+2  A: 

Are you able to init the constant in the class itself? Then just do this

class Cheese {

    const WHOA = 'me';

    public eat ()
    {
        return Cheese::WHOA; 

    }

}