简体   繁体   中英

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 = 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM