Domanda

  

Possibile duplicato:
   Passa una stringa PHP a una variabile Javascript (e sfuggire a nuove righe)

Ho diverse costanti in un'applicazione PHP che sto sviluppando. Ho definito una classe Costanti e definito le costanti come const VAR_NAME = value; in questa classe. Vorrei condividere queste costanti tra il mio codice JavaScript e PHP. Esiste un meccanismo DRY (Don't Repeat Yourself) per condividerli?

class Constants {
    const RESOURCE_TYPE_REGSITER = 2;
    const RESOURCE_TYPE_INFO = 1;
}
È stato utile?

Soluzione

Vorrei usare json_encode . Dovrai prima convertire la classe in un array associativo.

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

Puoi anche usare la riflessione per convertire la classe in un array associativo se preferisci usare una classe.

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

Altri suggerimenti

Inserisci un elenco di costanti comuni sia a JavaScript che a PHP in " client_server_shared.js " ;.

'var' è richiesto in JavaScript ed è legale (sebbene deprecato) in PHP se all'interno di una classe. '$' per iniziare un nome variabile è richiesto in PHP e legale in JavaScript.

var $shared_CONSTANT1 = 100;
var $shared_CONSTANT2 = 'hey';

Codice PHP:

eval('class Client_server_shared{'                   ."\n"
.     file_get_contents( 'client_server_shared.js' ) ."\n"
.    '}'
.    '$client_server = new Client_server_shared();'
);

echo $client_server->shared_CONSTANT1;   // Proof it works in PHP.
echo $client_server->shared_CONSTANT2;

Codice JavaScript:

alert( $shared_CONSTANT1 );              // Proof it works in JavaScript.
alert( $shared_CONSTANT2 );

L'unico modo in cui puoi condividere le costanti è che il lato php informi il javascript. Ad esempio:

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

O usando ajax, potresti anche scrivere un piccolo script che restituirebbe le costanti come JSON / qualunque cosa.

Un po 'di un brutto hack, ma qui va:

constants.js

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

constants.html (usa JavaScript)

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

constants.php (utilizzare all'interno di PHP)

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

echo $const1;
?>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top