58

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

感觉好像还有另一种更有效的方法可以做到这一点:

配置文件

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.

索引.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.

任何建议、建议或方向将不胜感激。谢谢。

4

2 回答 2

59

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

但是您可以使用array_fill_keys缩短它,如下所示:

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

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

于 2012-10-14T07:12:20.637 回答
2

第一个文件:

class config {
    public static $database = array();
}

其他文件:

config::$database = array(
    'driver' => 'mysql',
    'dbhost' => 'localhost',
    'dbname' => 'test_database',
    'dbuser' => 'testing',
    'dbpass' => 'P@$$w0rd'
);
于 2012-10-14T07:13:46.567 回答