我有一个有4个方法的php类。所有 4 种方法都使用一些通用变量,我已将这些变量创建为实例变量。但是我收到类似"未定义的变量:"之类的错误,我该如何解决这个问题。我的代码是,
public class test{
public static $variable;
public function func(){
$variable = "Hello World";
print_r($variable);
}
}
实际上,此代码不会给您任何错误,因为您只是打印您在打印语句上方定义的变量。
演示 : http://sandbox.onlinephpfunctions.com/code/cd43e866591ee0693cdcbeec6a230f583f756a67
如果要将值分配给函数上方定义的$variable
请尝试以下代码:
<?php
class test {
public static $variable;
public function func(){
self::$variable = "Hello World";
print_r(self::$variable);
}
}
$n = new test();
echo $n->func();
?>
演示 : http://sandbox.onlinephpfunctions.com/code/f11b726a678b9a5ee0e474d7ca194bb5ed75af22
如果该变量具有相同的静态值,请尝试此操作
class test
{
const variable ="Hello World";
public function func()
{
echo self::variable;
}
}
$name = new test;
$name->func();