PHP ↔ JavaScript communication : constants VS strings
<p>I am developping a web-application which makes a heavy use of AJAX. The server often answer by an array in order to <em>concatenate</em> different parts of the response.</p>

<p>I wonder what is the best solution to handle the keys in those arrays among the following two (the JSON encoding and decoding aren't shown):</p>

<h3>Strings</h3>

<p>This solution is easy to read, especially in JavaScript, but is really brittle and hard to maintain.</p>

<p><em>PHP</em> :
</p>

<pre><code>&lt;?php
return array(
    'key_name_1' =&gt; 'foo',
    'key_name_2' =&gt; 'bar'
);
?&gt;
</code></pre>

<p><em>JavaScript</em> :
</p>

<pre><code>var result = ajax(...);
alert(result.key_name_1);
</code></pre>

<h3>Constants</h3>

<p>This is a solid solution, which allow for short and numeric keys, but it's heavy and hard to read (use Reflection to automatize the generation of JavaScript constants is not an acceptable solution in my case, and doesn't solve all the drawbacks anyway).</p>

<p><em>PHP</em> :
</p>

<pre><code>&lt;?php
class Answer
{
    const CONSTANT_1 = 1;
    const CONSTANT_2 = 2;
}

return array(
    Answer::CONSTANT_1 =&gt; 'foo',
    Answer::CONSTANT_2 =&gt; 'bar'
);
?&gt;
</code></pre>

<p><em>JavaScript</em> :
</p>

<pre><code>Answer.CONSTANT_1 = &lt;?php echo Answer::CONSTANT_1; ?&gt;
Answer.CONSTANT_2 = &lt;?php echo Answer::CONSTANT_2; ?&gt;

var result = ajax(...);
alert(result[Answer.CONSTANT_1]);
</code></pre>

<hr>

<p>According to you, what is the best choice?</p>
