Reputation: 21
I wonder if anyone can help out here, I'm trying to understand how use an objects properties across multiple non class pages,but I can't seem to be able to get my head around everything i have tried so far.
For example a class called person;
class person {
static $name;
}
but i have a number of different regular pages that want to utilize $name
across the board.
I have trying things like this;
pageone.php
include "person.php";
$names = new Person();
echo person::$name;
names::$name='bob';
pagetwo.php
include "person.php";
echo person::$name;
I can work with classes to the extent I'm OK as long as I am creating new instances every page, but how can make the properties of one object available to all, like a shared variable ?
Thanks
Upvotes: 2
Views: 574
Reputation: 22783
You need to initialize the static variable inside the class declaration itself:
class Person {
public static $name = 'bob';
}
Or, you need some bootstrapping mechanism, where you inititalize the static variable:
bootstrap.php:
Person::$name = 'bob';
and then in the pages:
// assuming, you preloaded the bootstrap somewhere first
$person = new Person();
echo $person::$name;
edit
Ugh, what was I thinking... the above won't even work. You can't access a static member like that on an instance. Only through a method, like so:
class Person
{
public static $name;
public function getName()
{
return self::$name;
}
}
// assuming, you preloaded the bootstrap somewhere first
$person = new Person();
echo $person->getName();
/end edit
Or as Pekka pointed out, use sessions to keep state.
But more importanty: what is the goal you are trying to achieve? If you want to maintain state of a Person object between different requests, then Pekka's route is the way to go, or alternatively use another persistance storage mechanism, like a DB, File, etc...
Because I presume you don't mean to have every single Person instance named 'bob' do you? I presume you mean to maintain state of a single Person instance.
So, concluding, you probably don't want to use a static member to begin with.
Upvotes: 0
Reputation: 449395
Every new instance of a PHP script "forgets" everything done in previous scripts. The usual way of establishing a "storage room" for data across page loads is sessions. A session is essentially a specific ID a user gets when visiting a page. That ID is stored in a cookie, or a GET variable that is appended to every URL. PHP keeps text files in a special directory that can contain session specific data. Every file is named using the session ID.
The PHP manual has a thorough introduction here.
pageone.php
session_start();
$_SESSION["name"] = "Bob",
pagetwo.php
session_start();
echo $_SESSION["name"]; // Bob
Now if you had an instantiated object, you could serialize it, store it in a session variable, and unserialize it back in the 2nd page. I don't think that can be done with static classes though. But this should be a good start.
Upvotes: 3