我是PHP新手,遇到了范围/更新变量的问题。以下是我的代码:
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
}
我尝试过这里提到的解决方案(使用global,使用$GLOBALS,通过引用传递):从函数PHP内部更改全局变量,但都没有成功——不管怎样,第二个函数似乎没有得到类变量的更新版本。需要明确的是,我首先调用exampleFunction
,然后调用getter。
这:更改类变量的问题似乎是我的问题,但创建一个setter并传入对var
的引用没有任何作用,在任何其他函数中传入引用也没有任何作用(我不确定我是否完全理解它的工作原理)。
我不知道在这一点上该怎么办,任何帮助都将不胜感激。
编辑:以下是它的名称:
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');
}
});
}
示例中的Controller.php:
public static function getData() {
$result = ExampleClass::exampleFunction();
echo json_encode($result);
}
public static function getVar() {
$var = exampleClass::getVar();
echo json_encode($var);
}
试图获取从另一个函数更新的类变量
您的代码可以工作,只需先调用exampleFunction(),然后调用getVar()并重新分配返回的数组。并尝试修复if(something)
条件——这不是PHP错误,而是一个注意:使用未定义的常量之类的东西。
<?php
define('SOMETHING', true);
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
}
// add hello to the array ExampleClass::$var
ExampleClass::exampleFunction();
// get $var
$var = ExampleClass::getVar();
var_dump($var);
结果:
array(2) {
[0]=>
string(2) "hi"
[1]=>
string(5) "hello"
}
演示:https://ideone.com/4SiRnl