On Mon, 26 Nov 2001, Greg Sidelinger wrote:

> Can someone tell me how to store a class in a session var.   I want to

There are several things you need to do.

1) include the class definition before you do anything
2) start the session shortly thereafter
3) register a session variable
4) create your object
5) serialize your object
6) store the serialized object (now a string) in your registered session
   variable

Then to use the object again, you just have to

7) start the session back up
8) get the serialized value of your object from the registered session
   variable
9) unserialize the string value back into an object

Wanna see how this works?  I have a trivial example below, which involves
3 files.
- chair.class is my class definition.
- chair1.php sets up the session, creates the object, serializes and
  stores it in a registered session variable.
- chair2.php gets the session variable's value, unserializes it, and uses
  the object again.

-- chair.class
<?php
        class chair{

                // DATA MEMBERS
                var $num_legs;
                var $num_arms;

                // CONSTRUCTOR
                function chair( $legs = 3, $arms = 0 ){
                        $this->num_legs = $legs;
                        $this->num_arms = $arms;
                }

                // SETTERS
                function setLegs( $legs ){
                        $this->num_legs = $legs;
                        return true;
                }

                function setArms( $arms ){
                        $this->num_arms = $arms;
                        return true;
                }

                // GETTERS
                function getLegs( ){
                        return $this->num_legs;
                }

                function getArms( ){
                        return $this->num_arms;
                }
        }
?>

-- chair1.php

<?php
        include( "chair.class" );

        session_start();

        $myChair = new chair( 5, 3 );

        print( "My chair has " . $myChair->getLegs() . " legs, and " .
$myChair->getArms() . " arms." );

        $serChair = serialize( $myChair );

        session_register( "aChair" );

        $aChair = $serChair;
?>

-- chair2.php

<?php
        include( "chair.class" );

        session_start();

        $myChair = unserialize( $aChair );

        print( "My chair has " . $myChair->getLegs() . " legs, and " .
$myChair->getArms() . " arms." );

?>

        g.luck,
        ~Chris                           /"\
                                         \ /     September 11, 2001
                                          X      We Are All New Yorkers
                                         / \     rm -rf /bin/laden


-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
To contact the list administrators, e-mail: [EMAIL PROTECTED]

Reply via email to