Using objects throughout the application

Hi I have one page where I configured an object of class User.

$id = $_SESSION['user_id'];
$current_user =  new User();
$current_user->getFromID($id);

I tried to access this object from another page, but it looks empty. Is there any special way to do this?

+3
source share
3 answers

You also need to save the object to the session.

$_SESSION['user_id'] = $current_user;

Remember to include the user class definition (probably in its own file, right?) On all pages that use the session, otherwise the User object may get corrupted.

+4
source

Store the object in a session. To do this, your object must implement the __ sleep () / __ wakeup () functions .

, , __wakeup(). :

:

<?php //included file
class User {
  private $user_id;
  function getFromID($id) {... doing something; }
  function __wakeup() { 
     $this->getFromID($this->user_id);
  }
}

/ ;

<?php //some page
$current_user = $_SESSION['user'];
if(!$current_user) $current_user = new User();
...
$_SESSION['user'] = $current_user;
+2

If your object has some kind of state, you can save it in a session.
This is a way to pass variables between scripts in PHP.

But if it is not, just initialize it again.

0
source

Source: https://habr.com/ru/post/1748527/


All Articles