【问题标题】:php setter and getter not workingphp setter 和 getter 不工作
【发布时间】: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'); 添加到每个文件中,但这无济于事。

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

感谢任何反馈。谢谢。

【问题讨论】:

    标签: php oop get set


    【解决方案1】:

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

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

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

    【讨论】:

    • 也可以使用会话,但这是正确的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-03
    • 2022-07-21
    相关资源
    最近更新 更多