[英]Can the value of an item in a PHP associative array be created from values in the array?
I have a config.php as part of a web project which includes a multidimensional associative array.我有一个 config.php 作为 web 项目的一部分,该项目包括一个多维关联数组。
$config = array(
"db" => array(
"server" => "localhost",
"name" => "mydb",
"user" => "user",
"pwd" => "password"
),
"urls" => array(
"base_url" => "http://localhost/"
),
# Omitted for brevity
);
Under the 'db' array I'd like to include a key called 'dsn' which would be a PDO DSN string defined within the array itself.在“db”数组下,我想包含一个名为“dsn”的键,它是在数组本身中定义的 PDO DSN 字符串。 The only way I've managed to do this is defining it separately:
我设法做到这一点的唯一方法是单独定义它:
$config['db']['dsn'] = 'mysql:host=' . $config['db']['server'] . ';dbname=' . $config['db']['name'] . ';port=3306';
Is there anyway this could be defined in the array itself, like below?无论如何这可以在数组本身中定义,如下所示?
...
"db" => array(
"server" => "localhost",
"name" => "mydb",
"user" => "user",
"pwd" => "password"
"dsn" => #(some value here that uses "server" and "name")
),
...
If You want the array dsn
to update when u make change to $config
, then you can use class with magic methods or the ArrayAccess interface.如果您希望在更改
$config
时更新数组dsn
,那么您可以使用 class 和魔术方法或ArrayAccess接口。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.