views:

207

answers:

2

How do guys suggest to share a constants file between PHP and JavaScript, in order not to repeat code? XML file? I am assuming mixing up javascipt inside PHP would not be the right solution!? Thanks

+2  A: 

http://php.net/manual/en/book.json.php

I would say use json. It is native to the javascript and there is a parser library for the php.

consider the following:

json:

{constants : { var1 : "value 1", var2 : "value 2", var3 : "value 3"}}

and then read it into php:

$const = json_decode(json_string);

This gives you the object $const with properties like $const->{'var1'} returning "value 1".

in JavaScript this would be:

var const = eval(json_string);

and would give you const.constants.var1 == "value 1".

Easiest implementation in real terms for js is:

<script type="text/javascript" src="json_constants_file.js"></script>

When added the html output you instantly have a constants object with the other objects as its children.

Gabriel
+1 Seems like the simplest solution. @OP: On the Javascript side, you can either load the constants separately, or (since that seems wasteful) have a build process that pre-pends them to your Javascript file (preceded by `var constants = ` and followed by `;` to make the expression work).
T.J. Crowder
Just to make sure I understood, I would first read in PHP with file_get_contents the constants file, and then, inside the script tags I would do var constants = "the result string" ?
Luis
and would I have to do that in every php file on my site?
Luis
actually you could lazy load the json file as javascript and just work with the objects directly if that is what you needed. I would probably just create a php file for loading constants and include it where I needed it.
Gabriel
I edited it to be more of an example. Hope that helps.
Gabriel
A: 

Config variables to be shared by both PHP and JavaScript could easily be stored as XML, yes. JSON might be a better solution, though, as it requires minimal effort to parse - JS handles it natively, and PHP turns it into an array with json_decode.

ceejayoz