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";
}
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";
}
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.
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);
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.