58

本やウェブで、連想配列を名前だけで(空の値で)適切に初期化する方法を説明している例を見つけることができません-もちろん、これが適切な方法でない限り(?)

これを行うための別のより効率的な方法があるかのように感じます。

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.

推奨事項、提案、または指示をいただければ幸いです。ありがとう。

4

2 に答える 2

59

あなたが持っているのは、最も明確なオプションです。

ただし、次のようにarray_fill_keysを使用して短縮できます。

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

しかし、とにかくユーザーが値を入力する必要がある場合は、配列を空のままにして、index.php にサンプル コードを提供するだけで済みます。値を割り当てると、キーが自動的に追加されます。

于 2012-10-14T07:12:20.637 に答える
2

最初のファイル:

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

その他のファイル:

config::$database = array(
    'driver' => 'mysql',
    'dbhost' => 'localhost',
    'dbname' => 'test_database',
    'dbuser' => 'testing',
    'dbpass' => 'P@$$w0rd'
);
于 2012-10-14T07:13:46.567 に答える