2012-10-14 34 views
52

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

它只是感觉好像还有另一种更有效的方式来做到这一点(?):

的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'] = '[email protected]$$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. 

任何建议,意见或建议,将不胜感激。谢谢。

+0

嘿,并不重要,但你写 'DBNAME' - > '',它应该已经 'DBNAME'=>' ' - 我没有足够的声望来进行编辑。 – Martha

回答

47

你有什么是最明确的选择。

但你可以把它用array_fill_keys,像这样缩短:

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

但是,如果用户有反正填补值,你可以离开阵列空的,只是提供索引示例代码。 PHP。当您分配一个值时,这些键将自动添加。

+0

但是,您必须在课程之外执行此操作,因为您无法在类变量声明中调用任何函数。 *可能会导致更多的代码或初始化代码出现在您不希望看到的地方。 – BoltClock

+0

这就是我一直在寻找的!谢谢! – NYCBilly

+0

@BoltClock是的,我不会选择这个选项。那些'正常'数组初始化所需的额外字符使我更清楚代码的作用。我会保持原样。只是表明,如果你想,有办法做到这一点。 :)你可以在构造函数中做到这一点,但当然不能用于静态类。 – GolezTrol

1

第一个文件:

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

其他文件:

config::$database = array(
    'driver' => 'mysql', 
    'dbhost' => 'localhost', 
    'dbname' => 'test_database', 
    'dbuser' => 'testing', 
    'dbpass' => '[email protected]$$w0rd' 
); 
+0

这是硬编码,我的第二个文件只是一个例子 - 我需要已经定义的键。 – NYCBilly