php-setter和getter不工作


php setter and getter not working

我的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 />;

打印CCD_ 2。

我已经将include('test.php');添加到每个文件中,但这没有帮助。

我的代码中有错误吗?这也是正确的方法吗?如果不是,那是什么?

如有任何反馈,我们将不胜感激。谢谢

对象不是自动持久化的,您需要将数据存储在test2.php中,并使用数据库、表单或cookie在test3.php中检索数据。

我添加了include('test.php');到每个文件,但这没有帮助。

可能是因为您正在创建一个新的测试实例,该实例会覆盖test.php 中的实例