php - 使用键名但空值初始化关联数组

标签 php arrays initialization associative

我无法在书籍或网络上找到任何示例来描述如何仅通过名称(使用空值)正确初始化关联数组 - 当然,除非这是正确的方法(?)

感觉好像还有另一种更有效的方法:

config.php

class config {
    public static $database = array (
        'dbdriver' => '',
        'dbhost' => '',
        'dbname' => '',
        'dbuser' => '',
        'dbpass' => ''
    );
}

// Is this the right way to initialize an Associative Array with blank values?
// I know it works fine, but it just seems ... longer than necessary.

index.php

require config.php

config::$database['dbdriver'] = 'mysql';
config::$database['dbhost'] = 'localhost';
config::$database['dbname'] = 'test_database';
config::$database['dbuser'] = 'testing';
config::$database['dbpass'] = 'P@$$w0rd';

// This code is irrelevant, only to show that the above array NEEDS to have Key
// names, but Values that will be filled in by a user via a form, or whatever.

如有任何建议、建议或方向,我们将不胜感激。谢谢。

最佳答案

你所拥有的是最明确的选择。

但您可以使用 array_fill_keys 缩短它,像这样:

$database = array_fill_keys(
  array('dbdriver', 'dbhost', 'dbname', 'dbuser', 'dbpass'), '');

但如果用户必须填写值,您可以将数组留空,并在 index.php 中提供示例代码。分配值时会自动添加键。

关于php - 使用键名但空值初始化关联数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12880026/

相关文章:

c - 在声明以外的时间初始化 C 数组?

python - 像类一样初始化字典

arrays - 如何生成数字序列

php - 调试 iconv_strlen 错误 - PHP 5.5

php - 一个查询而不是多个

javascript - Angular : Unable to find the index of an array

arrays - 向数组添加哈希

c# - 使用 'with' 关键字复制记录结构时重新初始化仅获取属性

PHP更新记录时程序异常终止

php - SQL/PHP 从关注您的人中选择您不关注的关注者