·  PHP – Terms – Session – Variable – Create – Object

 

- Info:

  - This tutorial shows how to store Object into session and retreive it.

  - Before you can store object into session you have to serialize it, which means transform it into string.

    This way only object fields will be trasnformed and methods will be lost.

  - To retreive Object from session you have to deserialize it.

 

- Example:

  - Create PHP Console Application Test.php.

 

    Test.html

    <?php

   

      //ENABLE AUTOMATIC SESSION HANDLING.

      session_start();

    

      //CREATE OBJECT.

      $myObject   = new MyClass();

      

      //CONVERT OBJECT TO STRING. ONLY FIELDS ARE CONVERTED.

      $serialized = serialize($myObject);

      

      //SAVE SERIALIZED OBJECT AS SESSION VARIABLE.

      $_SESSION['serialized'] = $serialized;

      

      //RETREIVE SERIALIZED OBJECT FROM SESSION VARIABLE.

      $retreive = $_SESSION['serialized'];

      echo($retreive."<br>");

   

      //CONVERT STRING TO OBJECT.

      $unserialized = unserialize($retreive);

      echo("var=".$unserialized->var."<br>");

      print_r($unserialized);

      

      //DEFINE CLASS.

      class MyClass {

      

        public $var = "Hello from object!\n";

        

        public function displayString() {

          echo("Hello from classs!\n");

        }   

          

      }

      

    ?>

 

    output1

    O:7:"MyClass":1:{s:3:"var";s:19:"Hello from object! ";}
    var=Hello from object! 
    MyClass Object ( [var] => Hello from object! )