Reputation: 2047
i have 3 files
class.myclass.php contains
class myclass
{
public $value;
function assign($input)
{
$this->value=$input;
}
function show()
{
echo $this->value;
}
}
$obj=new myclass();
test1.php contains
require("class.myclass.php");
$obj->assign(1);
$obj->show();
test2.php contains
require("class.myclass.php");
$obj->show();
In test2.php the method $obj->show();
does not show the value that the method $obj->assign(1);
has assigned in test1.php
I think when i run test2.php the object $obj gets created again so the assigned value gets away. Is there any ways to save the state of the objects, so i can use from other php pages
Your help will greatly be appreciated. Thanks !!
Upvotes: 0
Views: 9346
Reputation: 1703
One technique that I've used on my projects is to create a good class constructor. By that, I mean create a constructor that can re-create the same object with a single argument.
For example:
class User {
public $email;
public $username;
public $DOB;
function __construct($input) {
// by providing a single input argument, we can re-create the object...
$this->email = $input;
$userData = $this->getUserData();
$this->username = $userData['username'];
$this->DOB = $userData['DOB'];
}
function getUserData() {
$email = $this->email;
$array = ["username" => "", "DOB" => ""];
// Database query/queries to get all user info for $email go here...
return $array;
}
}
now you can recreate the object if you store $email as the $_SESSION variable, for example:
file1.php
<?php
session_start();
$email = "[email protected]";
$_SESSION['user'] = $email;
file2.php
<?php
session_start();
include('User.class.php'); // this is the class example above
$email = $_SESSION['user'];
$userObject = new User($email);
// now you can access the object again as you need...
// for example:
$username = $userObject->username;
echo "Welcome back " . $username;
Upvotes: 2
Reputation: 360602
The easiest way is to save the object in serialized form in a $_SESSION variable, so it's auto-preserved between hits on your site.
test1.php:
session_start();
require('class.myclass.php');
$obj->assign(1);
$_SESSION['myobj'] = serialize($obj);
test2.php:
session_start();
$obj = unserialize($_SESSION['myobj']);
$obj->show();
For such a simple object, that's all that's needed. If your object contains resource handles (mysql connections, curl objects, etc...) then you'll need some extra logic in there to handle restoring those connections when the object is revived at unserialize time.
However, you may want to reconsider auto-instantiating your object in the class file, or at least make it into a singleton object, so your class file can be included in multiple places without the last-time-around $obj getting overwritten each time you re-include the file.
Upvotes: 6