当我尝试运行脚本时,即使它在全局范围内定义,我的ONE,TWO和THREE变量也是未定义的。我的A,B和C变量被认为是定义的。起初我以为是因为我将常量值指定为键,但我没有在网上找到任何表示我不能这样做的内容。
<?php class aClass
{
const A = 1;
const B = 2;
const C = 3;
const ONE = 1;
const TWO = 2;
const THREE = 3;
public $arr = [];
function __construct() {
$this->createArray();
}
function createArray() {
$this->arr[] = $this->A = [
$this->ONE => 'one.',
$this->TWO => 'two',
$this->THREE => 'three'
];
$this->arr[] = $this->B = [
$this->ONE => 'one',
$this->TWO => 'two',
$this->THREE => 'three',
];
$this->arr[] = $this->C = [
$this->ONE => 'one',
$this->TWO => 'two',
$this->THREE => 'three',
];
}
}
?>
答案 0 :(得分:5)
您已在aClass
课程中定义了常量而非属性。您必须将$this->ONE
替换为self::ONE
答案 1 :(得分:1)
您需要将createArray
中的常量从$this=>
更改为self::
,但仅此更改会导致语法错误:
$this->arr[] = self::A = [
self::ONE => 'one.',
self::TWO => 'two',
self::THREE => 'three'
];
会给你一个
解析错误:语法错误,意外'='
在这一行:
$this->arr[] = self::A = [`
// this ^ is the unexpected =
你提到使用常量值作为键, 你正在做什么
self::ONE => 'one.'
但不你正在做什么
$this->arr[] = self::A = [ ...
使用该行时,您没有使用self::A
作为键,您实际上是将以下数组分配给self::A
(这会导致“unexpected'='”错误,因为您无法将内容分配给常量),然后将self::A
分配给$this->arr[]
。
如果您想在self::A
中使用$this->arr
作为密钥,则需要这样做:
$this->arr[self::A] = [
self::ONE => 'one.',
self::TWO => 'two',
self::THREE => 'three'
];