dssqq64884 2013-01-03 09:00
浏览 60
已采纳

在php中使用变量作为关联数组值的错误

For some reason this is giving me the follow error: syntax error, unexpected T_VARIABLE:

 $mysql = json_decode(getenv("VCAP_SERVICES"));
 $mysql = $mysql["mysql-5.1"][0]["credentials"];

class DATABASE_CONFIG {

    public $default = array(
        'datasource' => 'Database/Mysql',
        'persistent' => false,
        'host' => 'localhost',
        'port' => $mysql['port'],  // <-- Line with error
        'login' => $mysql['username'],
        'password' => $mysql['password'],
        'database' => $mysql['name'],
        'prefix' => ''
        //'encoding' => 'utf8',
    );

    public $test = array(
        'datasource' => 'Database/Mysql',
        'persistent' => false,
        'host' => 'localhost',
        'login' => 'user',
        'password' => 'password',
        'database' => 'test_database_name',
        'prefix' => '',
        //'encoding' => 'utf8',
    );
}

I know you can use variables as values in arrays, so what is going on?

  • 写回答

3条回答 默认 最新

  • douhezi2285 2013-01-03 09:04
    关注

    It looks like you're trying to set the default value of a property to a variable.

    You can't do that, not even inside an array. This is half PHP's parser sucking, a quarter of PHP's lack of appropriate error message, and a bit of sanity.

    You'll need to do it from within the constructor instead by passing in $mysql:

    $config = new DATABASE_CONFIG($mysql);
    
    class DATABASE_CONFIG {
    
        public $default = array(
            'datasource' => 'Database/Mysql',
            'persistent' => false,
            'host' => 'localhost',
            'port' => null,
            'login' => null,
            'password' => null,
            'database' => null,
            'prefix' => ''
            //'encoding' => 'utf8',
        );
    
        public function __construct($mysql) {
            $this->default['port'] = $mysql['port']; // etc
        }
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?