使用键名称初始化关联数组,但使用空值

我无法在书籍或网页上find任何例子,描述如何正确地初始化一个关联数组(只有名称)(空值) – 当然,除非这是正确的方法(?)

它只是觉得有一个更有效的方法来做到这一点:

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. 

任何build议,build议,或方向将不胜感激。 谢谢。

你有什么是最明确的select。

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

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

但是,如果用户必须填写值,则可以将数组保留为空,只需在index.php中提供示例代码即可。 当您分配一个值时,这些键将自动添加。

第一个文件:

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

其他文件:

 config::$database = array( 'driver' => 'mysql', 'dbhost' => 'localhost', 'dbname' => 'test_database', 'dbuser' => 'testing', 'dbpass' => 'P@$$w0rd' );