Matt Scott Gibbs
Matt Scott Gibbs

Reputation: 55

php setter and getter not working

My php getters and setter dont seem to be working properly. Here is my code. The file test.php contains the following...

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. 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.

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.

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

The name is is printed.

I have added 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.

Upvotes: 0

Views: 1648

Answers (1)

Tom Tom
Tom Tom

Reputation: 3698

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.

I have added 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

Upvotes: 3

Related Questions