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

Asked

Viewed 418 times

-1

I create the variable:

$Client = new SoapClient(...);

And then:

$_SESSION["Cliente"] = $Client;

Not to have to make a complete request on each page.

Is there such a possibility?

  • I never tried, but I probably didn’t see the need for the question, because you were the only one who would have answered your question. Depending on the class, it would be better to turn it into static.

  • Working with TCP/IP Chat sometimes we need to maintain a persistent connection, in my case I make a connection on a Webservice and would like to know if there is a way to maintain this connection while the user is in the restricted area, so when it changes pages I don’t need to keep redoing the connection but only perform the functions to get return. I took the test and I couldn’t, but I may have a way of doing it, so my question.

  • 3

    Possible duplicate of Sending an object through Session

3 answers

4

Yes it is possible.

Even you don’t need to use any additional function.
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();
    ?>

1

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

Yes, there is the possibility to keep an object saved. Read about the method serialize, he returns a string with the data represented on the object. To turn the string into an object, the method is used unserialize.

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";}"
*/

This way, you can save the serialized object in the session:

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

And rescue him:

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

See on ideone

1

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

By assigning the superglobal:

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

To assign from superglobal to another variable:

$var_destino = unserialize($_SESSION['Cliente'])

Browser other questions tagged

You are not signed in. Login or sign up in order to post.