【问题标题】:PHP 5.6.3 Parse error: syntax error, unexpected '[' in classPHP 5.6.3 解析错误:语法错误,类中出现意外的“[”
【发布时间】:2015-03-09 08:17:42
【问题描述】:

当我在 php 中创建一个类时,我遇到了这个错误:

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!

我能做什么?我只是失明了吗?

【问题讨论】:

  • 我不认为你可以这样做,但试试$variable = array("attribute" =&gt; "I'm a class property!")
  • 我知道这种方式可行,但为什么在课堂之外可能呢?
  • 只是因为它在类之外......它会隐式创建数组并设置它的元素,但在这里看起来你正在将数组的“属性”元素声明为公共,即很奇怪,php 也不喜欢它
  • 好吧,有点混乱,但我想我明白了!

标签: php arrays php-parse-error


【解决方案1】:

我想你应该像下面这样声明它:

class MyClass
{
   public $variable = array( "attribute" => "I'm a class property!" );
}

【讨论】:

    【解决方案2】:

    您不能显式创建这样的变量(数组索引)。你必须这样做:

    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();
    

    【讨论】:

      【解决方案3】:

      先做一个数组。使用下面的代码

      <?php
      
      class MyClass
      {
      public $variable = array("attribute"=>"I'm a class property!");
      
      }
      
      ?>
      

      希望对你有帮助

      【讨论】:

        【解决方案4】:

        你不能这样声明类成员。您也不能在类成员声明中使用表达式。

        有两种方法可以实现您的目标:

        class MyClass
        {
            public $variable;
            function __construct()
            {
                $variable["attribute"] = "I'm a class property!";
            }
        }
        

        或者像这样

        class MyClass
        {
            public $variable = array("attribute" => "I'm a class property!");
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-04-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-05-28
          • 1970-01-01
          • 2013-01-11
          相关资源
          最近更新 更多