I am creating a JavaScript based game with PHP, and need help storing the user's account object. Once I construct the player object in JavaScript, how can I use this object throughout every page?
I have tried to add the user's account object to the window object, but did not have any luck. This code is placed in the menu which is used on all pages.
if (isset($_SESSION['userId'])) {
$user = $_SESSION['user'];
echo '<script>
if (typeof window.user != "undefined") {
console.log("user is defined from before.");
console.log(window.user);
} else {
var user = new Player('.$user->{'id'}.',"'.$user->{'username'}.'");
window.user = user;
console.log("A new user was created.");
console.log(window.user);
}</script>';
}
Each time a page is loaded, a new player is created and added to the window object. I expected "window.user" to be defined after adding the user's account object.
Here is my Player object constructor as well
function Player (id, username) {
this.id = id,
this.username = username,
this.resources = {
hydrogen: 0,
helium: 0,
carbon: 0,
nitrogen: 0,
oxygen: 0,
sodium: 0,
magnesium: 0,
aluminium: 0,
silicon: 0,
sulfur: 0,
calcium: 0,
titanium: 0,
cobalt: 0,
nickel: 0,
copper: 0,
krypton: 0,
palladium: 0,
silver: 0,
platinum: 0,
gold: 0
},
this.currency = {
currency1: 0,
currency2: 0,
currency3: 0,
currency4: 0,
currency5: 0
},
this.starter = 0
}