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条)

报告相同问题?

悬赏问题

  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥15 QT6颜色选择对话框显示不完整
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥15 DS18B20内部ADC模数转换器