Skip to content

Instantly share code, notes, and snippets.

@bappi-d-great
Created June 14, 2020 12:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bappi-d-great/b44c35896eeb5f5d70466dc67639a198 to your computer and use it in GitHub Desktop.
Save bappi-d-great/b44c35896eeb5f5d70466dc67639a198 to your computer and use it in GitHub Desktop.
Passing php data to external JS file
<?php
class Localize {
private $_data = [];
private function __construct () {}
static public function get_instance() {
static $Inst = null;
if( $Inst === null ) {
$Inst = new self();
}
return $Inst;
}
public function push( $key, $val ) {
$this->_data[$key] = $val;
}
public function pull( $key ) {
unset( $this->_data[$key] );
}
public function data() {
return json_encode( $this->_data );
}
public function print() {
echo $this->data();
}
}
function lc() {
return Localize::get_instance();
}
lc()->push( 'name', 'Ash' );
lc()->push( 'age', 32 );
lc()->push( 'job', 'Developer' );
?>
<script>
const data = JSON.parse( '<?php lc()->print(); ?>' );
console.log( data.name, data.age, data.job );
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment