如何在PHP的类属性中使用类常量

如何在PHP的类属性中使用类常量

本文介绍了如何在PHP的类属性中使用类常量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是不起作用的代码:

class MyClass
{
    const myconst = 'somevalue';

    private $myvar = array( 0 => 'do something with '.self::myconst );
}

似乎类常量在编译时"不可用,而仅在运行时可用.有人知道有什么解决方法吗? (定义将无效)

Seems that class constants are not available at "compile time", but only at runtime.Does anyone know any workaround ? (define won't work)

谢谢

推荐答案

类声明中的问题不是使用常量,而是使用表达式.

The problem in your class declaration is not that you are using a constant, but that you are using an expression.

例如,此简单声明将不会编译(解析错误):

This simple declaration, for example, will not compile (parse error):

class MyClass{
    private $myvar = 3+2;
}

但是,如果我们更改类声明以使用简单常量,而不是使用与该常量串联的字符串,它将按预期工作.

But if we alter your class declaration to use the simple constant, rather than a string concatenated with that constant it will work as expected.

class MyClass{
    const myconst = 'somevalue';
    public $myvar = array( 0 => self::myconst );
}

$obj = new MyClass();
echo $obj->myvar[0];

作为解决方法,您可以在构造函数中初始化属性:

As a work-around you could initialize your properties in the constructor:

class MyClass{
    const myconst = 'somevalue';
    public $myvar;

    public function __construct(){
        $this->myvar = array( 0 => 'do something with '.self::myconst );
    }
}
$obj = new MyClass();
echo $obj->myvar[0];

希望这对您有帮助,
阿林

I hope this helps you,
Alin

这篇关于如何在PHP的类属性中使用类常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 07:41