我无法在书籍或网络上找到任何示例来描述如何仅通过名称(使用空值)正确初始化关联数组 - 当然,除非这是正确的方法(?)
感觉好像还有另一种更有效的方法:
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/