PHP 5.6.3 Parse error: syntax error, unexpected '[' in class
PHP 5.6.3 Parse error: syntax error, unexpected '[' in class
当我在 php 中创建 class 时,我遇到了这个错误:
Parse error: syntax error, unexpected '[', expecting ',' or ';' on line 5
一个简单的例子:
<?php
class MyClass
{
public $variable["attribute"] = "I'm a class property!";
}
?>
我已经看过 Reference - What does this error mean in PHP? 但这似乎不适合我的情况。所有其他现有问题的问题似乎都依赖于旧的 PHP 版本。但是我正在使用 PHP 5.6.3!
我能做什么?我只是瞎了眼吗?
我猜你应该按照下面显示的方式声明它:
class MyClass
{
public $variable = array( "attribute" => "I'm a class property!" );
}
您不能显式创建这样的变量(数组索引)。你必须这样做:
class MyClass {
// you can use the short array syntax since you state you're using php version 5.6.3
public $variable = [
'attribute' => 'property'
];
}
或者,您可以这样做(就像大多数人那样):
class MyClass {
public $variable = array();
function __construct(){
$this->variable['attribute'] = 'property';
}
}
// instantiate class
$class = new MyClass();
先做一个数组。使用下面的代码
<?php
class MyClass
{
public $variable = array("attribute"=>"I'm a class property!");
}
?>
希望这对你有帮助
您不能像这样声明 class 成员。您也不能在 class 成员声明中使用表达式。
有两种方法可以达到您的要求:
class MyClass
{
public $variable;
function __construct()
{
$variable["attribute"] = "I'm a class property!";
}
}
或者像这样
class MyClass
{
public $variable = array("attribute" => "I'm a class property!");
}
当我在 php 中创建 class 时,我遇到了这个错误:
Parse error: syntax error, unexpected '[', expecting ',' or ';' on line 5
一个简单的例子:
<?php
class MyClass
{
public $variable["attribute"] = "I'm a class property!";
}
?>
我已经看过 Reference - What does this error mean in PHP? 但这似乎不适合我的情况。所有其他现有问题的问题似乎都依赖于旧的 PHP 版本。但是我正在使用 PHP 5.6.3!
我能做什么?我只是瞎了眼吗?
我猜你应该按照下面显示的方式声明它:
class MyClass
{
public $variable = array( "attribute" => "I'm a class property!" );
}
您不能显式创建这样的变量(数组索引)。你必须这样做:
class MyClass {
// you can use the short array syntax since you state you're using php version 5.6.3
public $variable = [
'attribute' => 'property'
];
}
或者,您可以这样做(就像大多数人那样):
class MyClass {
public $variable = array();
function __construct(){
$this->variable['attribute'] = 'property';
}
}
// instantiate class
$class = new MyClass();
先做一个数组。使用下面的代码
<?php
class MyClass
{
public $variable = array("attribute"=>"I'm a class property!");
}
?>
希望这对你有帮助
您不能像这样声明 class 成员。您也不能在 class 成员声明中使用表达式。
有两种方法可以达到您的要求:
class MyClass
{
public $variable;
function __construct()
{
$variable["attribute"] = "I'm a class property!";
}
}
或者像这样
class MyClass
{
public $variable = array("attribute" => "I'm a class property!");
}