首页 > 解决方案 > 带有连接字符串的php关联数组声明

问题描述

我正在尝试将包含字符串的关联数组声明放入 80 列宽(样式指南)中。这是在一个抽象类中完成的。为了适应 80 列宽,我使用了 php 的连接运算符。请参阅以下代码片段。

原始代码格式:

abstract class VideoBase
{
  protected $config_types =
    array('production' =>'Configures all hardware for production runs',
          'development'=>'Configures project specific development connections if available. Otherwise, only out the window and heads down connections are made');
  function __construct()        
  {
    print_r($config_types);
  }    
  function __destruct()
  {
  }
}

尝试的代码格式:

abstract class VideoBase
{
  protected $config_types =
    array('production' =>'Configures all hardware for production runs',
          'development'=>'Configures project specific development connections '.
                         'if available. Otherwise, only out the window and '.
                         'heads down connections are made');
  function __construct()        
  {
    print_r($config_types);
  }    
  function __destruct()
  {
  }
}

我收到以下错误:PHP Parse error: syntax error, unexpected '.', expecting ')'

据我所知,上述语法是正确的。只有在抽象类中声明关联数组时才会发生解析错误。

我在做什么不正确地阻止了这种语法的工作?

答:正如下面接受的答案中所述,解析错误是由于 PHP Parser 版本不知道以这种方式完成时如何处理语法。我需要 PHP 5.6 或更高版本才能正常工作。

标签: php

解决方案


在 5.6 之前,您不能将标量值以外的任何内容声明为类属性。

没有函数调用,没有算术,也没有连接

如果既不是升级也不是简单地违反您的代码样式指南是一个选项,那么将该值分配移动到构造函数。

参考: http: //php.net/manual/en/migration56.new-features.php#migration56.new-features.const-scalar-exprs


推荐阅读