Is it possible to keep an object in a session variable?

-2

I create the variable:

$Client = new SoapClient(...);

And then:

$_SESSION["Cliente"] = $Client;

To not have to make a complete request to each page.

Is there a possibility?

    
asked by anonymous 06.07.2016 / 20:28

3 answers

3

Yes it is possible.

Even you do not have to use any additional functions. It would look something like this:

CLASS PERSON

<?php 
class Pessoa{
    public $name;
    public $idade;

    function count(){
        echo '123456';
    }
}?>

VIEW / CONTROLLER

    <?php 
        include("Pessoa.php");
        $pessoa = new Pessoa;
        $pessoa->nome = 'Ricardo';
        $pessoa->idade = 22;

        session_start();
        $_SESSION['pessoa'] = $pessoa;

        $_SESSION["pessoa"]->count();

        session_destroy();
    ?>
    
06.07.2016 / 21:23
1

For your situation, I believe that you should rethink the way your project is being developed, but answering your question:

Yes, there is the possibility of keeping a saved object. Please read the serialize method, it returns a string with the data represented in the object. To make the string an object, the unserialize method is used.

Exemplifying:

$object = new stdClass();
$object->hello = 'Hello world';

var_dump($object);

/*
object(stdClass)#1 (1) {
  ["hello"]=>
  string(11) "Hello world"
}
*/

var_dump(serialize($object));
/*
string(50) "O:8:"stdClass":1:{s:5:"hello";s:11:"Hello world";}"
*/

In this way, you can save the serialized object in the session:

$_SESSION["serializedObject"] = serialize($object);

And rescue him:

$sessionObject = unserialize($_SESSION["serializedObject"]);

See the ideone

    
06.07.2016 / 21:02
1

Hello, I did this some time ago and at the moment I have no way to test, if I'm not mistaken you should use the serialize () and unserialize ()

When assigning to superglobal:

$_SESSION['Cliente'] = serialize($client)

To assign from superglobal to another variable:

$var_destino = unserialize($_SESSION['Cliente'])
    
06.07.2016 / 21:02