开发者

OOP can't use define in variable

开发者 https://www.devze.com 2023-01-31 10:59 出处:网络
Why can\'t you use defines when creating a var开发者_如何学Goiable in a class? What can I do to get past this? (the define is a table prefix (db))

Why can't you use defines when creating a var开发者_如何学Goiable in a class? What can I do to get past this? (the define is a table prefix (db))

Like this:

class foo {
    public $bar = FOO."bar";
}

That gives me the following error:

Parse error: syntax error, unexpected '.', expecting ',' or ';'


You can only declare properties with constant expressions. Here, the concatenation operator is illegal (hence the parse error), not the FOO constant.

public $bar = FOO."bar";

One way past this is to initialize it in the constructor instead. You can still use the constant, along with concatenating it with your string.

class foo {
    public $bar;

    public function __construct() {
        $this->bar = FOO."bar";
    }
}


You can use the constructor to initialize the value:

<?php
define("FOO", "test");

class foo {
    public $bar;

    function __construct()
    {
        $this->bar = FOO . "bar";
    }
}

var_dump(new foo());


It's not that you cannot use defines. You cannot use operators when initializing variables.


As mentioned above, you cannot define class variables using operators, if the value needs to be dynamic, then the assignment must occur in a function.

When using constants, it can be useful to use class constants instead of defining your constants in the global scope. They're defined using the keyword const, and accessed using the self:: operator.

class foo 
{
    const BAR = 'test';

    public $baz;

    public function __construct()
    {
        $this->baz = self::BAR . 'bat';
    }

}

Class constants can also be accessed outside an instance statically: foo::BAR, so you can use constants from classes in other contexts, but are not automatically in the global scope as a constant defined with define.

$some_var = foo::BAR;
echo $some_var;
// output: test
0

精彩评论

暂无评论...
验证码 换一张
取 消