0

I have this example:

    class test_names {
        public name = 'ralph';

        function dispname() {
            return $this->name;
        }
    }

$test = new test_names;
$test->name = 'John';
$test->dispname;

now the result will be "John" because I saved that in de public var

Now I have another file called test2.php and I do this:

    $test = new test_names;
    $test->dispname;

the result will be "ralph" but I don't want that, I want it to be "John" (that value I've set before)

How can I make this happen?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Ralph Schipper
  • 701
  • 2
  • 12
  • 24
  • 1
    What's the relationship between the two php files? – Jon Jun 08 '14 at 12:11
  • 1
    Use a static variable `name`. – Artjom B. Jun 08 '14 at 12:13
  • Oh sorry, first file is called class.test_names.php, I put the class in here. Then I have a file called test1.php there I call the class and set the name to "john". And I have another file called test2.php: There I call the class and just display the name, and I want that to be "John" as I defined that in test1.php – Ralph Schipper Jun 08 '14 at 12:18
  • Are you executing test1.php and test2.php in the same hit? Otherwise you need a session. – Wolfgang Stengel Jun 24 '14 at 14:03

1 Answers1

0

Dont instanciate the class again as you already did it:

replace

   $test = new test_names;
   $test->dispname;

by

$test->dispname;
GouxLord
  • 86
  • 8
  • Yes I know, but I instanciate the class in test1.php and now I want to use the same clas also in test2.php so I do need to instanciate it in test2.php again right? – Ralph Schipper Jun 08 '14 at 12:24
  • 2
    There is a difference between classes and the objects your create from it (instances). When you `new Class` something you get an instance of that class. All the non-static properties are only for that instance. See http://stackoverflow.com/questions/2206387/what-is-a-class-in-php/2206835#2206835 – Gordon Jun 08 '14 at 12:48