Php 初始化具有键名但值为空的关联数组
我在书中或网络上找不到任何例子来描述如何仅按名称(使用空值)正确初始化关联数组,当然,除非这是正确的方法(?) 感觉好像还有另一种更有效的方法: config.phpPhp 初始化具有键名但值为空的关联数组,php,arrays,initialization,associative,Php,Arrays,Initialization,Associative,我在书中或网络上找不到任何例子来描述如何仅按名称(使用空值)正确初始化关联数组,当然,除非这是正确的方法(?) 感觉好像还有另一种更有效的方法: config.php class config { public static $database = array ( 'dbdriver' => '', 'dbhost' => '', 'dbname' => '', 'dbuser' => '',
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.
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.
index.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.
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.
如有任何建议、建议或指示,将不胜感激。谢谢。您拥有的是最清晰的选项 但您可以使用以下方法缩短它:
$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'
);
但是,您必须在类之外执行此操作,因为您不能在类变量声明中调用任何函数。这可能会导致更多的代码,或者初始化代码出现在您不希望看到的地方。这就是我一直在寻找的!谢谢大家!@是的,无论如何我都不会选择这个选项。“正常”数组初始化所需的这些额外字符使我更清楚地了解代码的作用。我会让它保持原样。只是表明,如果你愿意,有办法做到这一点。:)当然,你可以在构造器中实现这一点,但不能在静态类中实现。。。但我真正想要的是用缩短的方法来填充它们。看起来,虽然我得到了答案,但从上面的评论来看,原版是最好的选择。谢谢大家…我不知道数组填充键,虽然它有它的局限性,但这是一个非常好和有效的方法。这是硬编码的,我的第二个文件只是一个例子-我需要已经定义的键。嘿,不重要,但你已经在“dbname”=>“应该”的地方写了“dbname”->“-我没有足够的声誉来进行编辑。@玛莎-我按照你的建议进行了编辑。