I'm new to PHP and have run into an issue with scope/updating variables. Here is what my code looks like:
class ExampleClass {
private static $var = array("hi");
public static function exampleFunction() {
if(something) {
self::$var[] = "hello";
}
} //I print out this change and it works, containing both hi and hello
public static function getVar() {
return self::$var;
} //this does not return the updated array, only the original with hi
}
I've tried the solutions mentioned here (using global, using $GLOBALS, passing by reference): Changing a global variable from inside a function PHP but none of them have worked -- no matter what, it seems like the second function does not get the updated version of the class variable. To be clear, I am calling exampleFunction
first and then calling the getter.
This: Trouble changing class variable seems like it could be my problem, but creating a setter and passing in the reference to var
does nothing, nor does passing in a reference in any other function (I'm not sure I completely understand how it works).
I'm not sure what to do at this point, and any help would be appreciated.
EDIT: Here is how it's being called:
example.js:
$('#aButton').click(function() {
getData();
getVar();
});
function getData() {
$.ajax({
url: '/exampleController/getData',
success: function(response){
console.log(response);
alert("var success");
},
error: function(){
alert('Error');
}
});
}
function getVar() {
$.ajax({
url: '/exampleController/getVar',
success: function(response){
console.log(response);
alert("var success");
},
error: function(){
alert('Error');
}
});
}
in exampleController.php:
public static function getData() {
$result = ExampleClass::exampleFunction();
echo json_encode($result);
}
public static function getVar() {
$var = exampleClass::getVar();
echo json_encode($var);
}