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";
}
2

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

ist showing Parse error: syntax error, unexpected '['
@SheldonCooper Fixed, it only worked for 5.4 with the [] notation :)
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);

1 Comment

This has to be the best answer to the question so far. But as far as a realistic implementation, I agree with Jack.
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.