gpt4 book ai didi

php - 如何在 PHP 中将类常量用于类属性?

转载 作者:可可西里 更新时间:2023-10-31 23:10:18 24 4
gpt4 key购买 nike

这是行不通的代码:

class MyClass
{
const myconst = 'somevalue';

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

似乎类常量在“编译时”不可用,而仅在运行时可用。有谁知道任何解决方法? (定义不起作用)

谢谢

最佳答案

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

Class member variables are called "properties". (...) They are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration. This 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.

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

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

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

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

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

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

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];

希望对你有帮助,
阿林

关于php - 如何在 PHP 中将类常量用于类属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4297219/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com