简体   繁体   English

php setter和getter无法正常工作

[英]php setter and getter not working

My php getters and setter dont seem to be working properly. 我的php getter和setter似乎无法正常工作。 Here is my code. 这是我的代码。 The file test.php contains the following... 文件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 has a form which asks the user to enter their own name. test2.php具有要求用户输入自己的名称的形式。 When they click submit, I have code that looks like this to set the name they entered to the variable name in test. 当他们单击“提交”时,我将获得如下代码,将他们输入的名称设置为测试中的变量名称。

$test=test::getInstance();  
$test->setName("My PHP Test");
print "The name is " . $test->getName() . "<br />;

The name is My PHP Test is printed successfully. The name is My PHP Test成功打印。

However, once they submit a form on on test2.php which takes the user to test3.php and I try the same code to return the name, the value returned is null. 但是,一旦他们在test2.php上提交了一个表单,该表单会将用户带到test3.php,并且我尝试使用相同的代码返回名称,则返回的值为null。

$test=test::getInstance();  
print "The name is " . $test->getName() . "<br />;

The name is is printed. The name is已打印。

I have added include('test.php'); 我添加了include('test.php'); to each file but this doesn't help. 到每个文件,但这无济于事。

Is there an error in my code? 我的代码中有错误吗? And also is this the correct approach in general? 而且这通常是正确的方法吗? If not what is? 如果不是,那是什么?

Any feedback is appreciated. 任何反馈表示赞赏。 Thanks. 谢谢。

Objects aren't persisted automatically, you need to store the data in test2.php and retrieve it in test3.php, either using a database, a form or cookies. 对象不会自动持久化,您需要使用数据库,表单或cookie将数据存储在test2.php中,并在test3.php中检索它们。

I have added include('test.php'); 我添加了include('test.php'); to each file but this doesn't help. 到每个文件,但这无济于事。

Probably because you are creating a new instance of test that overwrites the one in test.php 可能是因为您正在创建一个新的test实例,该实例将覆盖test.php中的一个实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM