2

Is there any way to create array with key constants like mentioned below in php

class MysqlConstants
{
    const masterDb['HOST'] = "ip";
    const masterDb['user'] = "user";
}
Sheldon Cooper
  • 236
  • 4
  • 17

3 Answers3

5

No, this is not possible; class constants must be literals, not expressions. The closest alternative is static properties:

class MySqlConstants
{
    public static $masterDb = array('HOST' => "ip", 'user' => "user");
}

I personally don't like this approach because constants should be immutable. This would be a better approach:

class MySqlConstants
{
    private static $masterDb = array('HOST' => "ip", 'user' => "user");

    public final static function getMasterDb()
    {
        return self::$masterDb;
    }
}

Lastly you could just split up the constants:

class MySqlConstants
{
    const HOST = "ip";
    const user = "user";
}

Btw, storing configuration in code is not something I would recommended unless their application constants; it would be better to store connection settings, etc. in an ini file for instance, and use parse_ini_file() to retrieve it.

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
3

You can also serialize your array and then put it into the constant:

# define constant, serialize array
define ("CRED", serialize (array ("host"=>"ip", "user"=>"user")));

# use it
$my_credential = unserialize (CRED);
Praveen kalal
  • 2,148
  • 4
  • 19
  • 33
  • This has to be the best answer to the question so far. But as far as a realistic implementation, I agree with Jack. – Sam Apr 10 '13 at 05:55
0

I would suggest using define("MYSQL_HOST","ip"); in another php file called, lets say config.php so you can easily access it with MYSQL_HOST without calling instances of class or global $masterDb every time u want to use it.

Another advantage of having config.php is that you can easily modify common used variables.

Nikola R.
  • 1,173
  • 6
  • 23