【发布时间】:2015-02-15 23:52:03
【问题描述】:
我的 php getter 和 setter 似乎无法正常工作。这是我的代码。文件 test.php 包含以下内容...
class test{
private static $instance;
private $name=null;
public static function getInstance(){
if(!isset(test::$instance) ) {
test::$instance = new test();
}
return test::$instance;
}
public function setName($n){
$this->name=$n;
}
public function getName(){
return $this->name;
}
test2.php 有一个表单,要求用户输入他们自己的名字。当他们点击提交时,我有如下代码来将他们输入的名称设置为测试中的变量名称。
$test=test::getInstance();
$test->setName("My PHP Test");
print "The name is " . $test->getName() . "<br />;
The name is My PHP Test 打印成功。
但是,一旦他们在 test2.php 上提交了一个表单,该表单将用户带到 test3.php,我尝试使用相同的代码返回名称,返回的值为 null。
$test=test::getInstance();
print "The name is " . $test->getName() . "<br />;
The name is 被打印出来。
我已将include('test.php'); 添加到每个文件中,但这无济于事。
我的代码有错误吗?这也是一般的正确方法吗?如果不是,那是什么?
感谢任何反馈。谢谢。
【问题讨论】: