views:

620

answers:

3

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;
}
+1  A: 

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"));
Adam Peck
You mixed JavaScript and PHP syntax. There is no JSON object in PHP. There are just json_*() functions.
Gumbo
Oops. I have updated it so there is no confusion :D
Adam Peck
This is great, however, get_class_vars seems to skip the const variables in the class.
Brian Fisher
Heh. Nice patching.
Crescent Fresh
Hey at least it's right now :) Although I still think the simplest way is to leave it in an associative array. And this time I actually tested it too!
Adam Peck
Thanks, this works great. I like using the const member variables instead of an associative array, because my IDE can then do code completion.
Brian Fisher
A: 

The only way you can share the constants is to have the php side inform the javascript. For instance:

echo "<script> var CONSTANT1 =".$constant_instance->CONSTANT_NAME.";</script>";

Or using ajax, you could also write a small script that would return the constants as JSON/whatever.

jacobangel
A: 

A bit of an ugly hack, but here it goes:

constants.js

//<?php
$const1 = 42;
$const2 = "Hello";
//?>

constants.html (use inside JavaScript)

<script type="text/javascript" src="constants.js"></script>
<script type="text/javascript">document.write($const1);</script>

constants.php (use inside PHP)

<?php
ob_start(); // start buffering the "//"
require "constants.js";
ob_end_clean(); // discard the buffered "//"

echo $const1;
?>
Ates Goral
I knew this answer would get downvotes! :)
Ates Goral