Created
June 14, 2020 12:10
-
-
Save bappi-d-great/b44c35896eeb5f5d70466dc67639a198 to your computer and use it in GitHub Desktop.
Passing php data to external JS file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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