Share Constants Between PHP and JavaScript

Brian Fisher picture Brian Fisher · Jan 13, 2009 · Viewed 7.2k times · Source

Possible Duplicate:
Pass a PHP string to a Javascript variable (and escape newlines)

I have several constants in a PHP application I'm developing. I've defined a Constants class and the defined the constants as const VAR_NAME = value; in this class. I would like to share these constants between my JavaScript and PHP code. Is there a DRY (Don't Repeat Yourself) mechanism to share them?

class Constants {
    const RESOURCE_TYPE_REGSITER = 2;
    const RESOURCE_TYPE_INFO = 1;
}

Answer

Adam Peck picture Adam Peck · Jan 13, 2009

I would use json_encode. You will have to convert the class to an associative array first.

$constants = array("RESOURCE_TYPE_REGISTER"=>2, "RESOURCE_TYPE_INFO"=>2);
echo json_encode($constants);

You could also use reflection to convert the class to an associative array if you would prefer to use a class.

function get_class_consts($class_name)
{
    $c = new ReflectionClass($class_name);
    return ($c->getConstants());
}

class Constants {
    const RESOURCE_TYPE_REGSITER = 2;
    const RESOURCE_TYPE_INFO = 1;
}

echo json_encode(get_class_consts("Constants"));