What scope to php variables have with regards to AJAX calls? So for example, a file main.php creates an instance of a class Test:
<html>
<head>
<?php
require_once 'test.php';
$test = new Test('some parameter');
?>
</head>
<body></body>
</html>
Later on there is a jQuery post event triggered by some event:
$(document).ready(function() {
$.post(
"class/start.php",
function(data) {
// some functioning.
}, "json");
});
Then in start.php I need access to the class I defined in main.php. E.g.:
<?php
echo json_encode($test->SomeFunction());
?>
From testing this I’m fairly sure this isn’t possible. I assume the scope of $test dies when main.php comes from the server. So what do I need to do to access the instance of that class? Do I need to add $test as a session variable or is there some other better way?
You could
session_start()and put$testin$_SESSION['whatever'].You’ll need to
session_start()as the first thing in the php activity for both HTTP requests. In the second HTTP request, justjson_decode()the object and then add it to$_SESSION['whatever'].In case you’re not familiar with sessions, they basically give you the ability to retain state, storing state data in
$_SESSION[]. See here: http://www.php.net/manual/en/function.session-start.php