views:

144

answers:

4

Hay guys. I'm kinda new to OOP in PHP. I've learnt how to write and create objects. Is there a way to take an object and pass it to another script? either using GET or POST or SESSION or whatever. If there isn't how would i assign an object some variables on one page, then assign the same object more variables on another page?

Thanks

+1  A: 

You can use the $_SESSION. but it will only be for that session.

thephpdeveloper
+1  A: 

You could store the object in a SESSION. You can serialize the object and pass through GET or POST.

If you want the object to persist across the site, then SESSION is probably your best bet.

easement
Thanks, seems like SESSIONs are the best bet
dotty
+3  A: 

You can store objects in the session but you need to include the file which contains the class definition before calling session_start() (or use class autoloading and set this up before you start the session). For example:

On every page:

//include class definition
require('class.php');

//start session
session_start();

1st page:

$object = new class();
$object->someProperty = 'hello';

//store in session
$_SESSION['object'] = $object;

Subsequent pages:

$object = $_SESSION['object'];

//add something else, which will be stored in the session
$object->anotherPropery = 'Something';
Tom Haigh
Thanks! Perfect example. Also i didn't know about the __autoload method.
dotty
+1  A: 

Using an object on multiple 'scripts':

First, you have to decide what kind of structure your OOP application has. If you use something like MVC pattern, you do not have to this by using SESSION or REQUEST, because you can 'plug' the objects you want to use into 'one'. What does this mean?

A quick example:

  1. User A enters your site index.php
  2. Now you can load the content from a static index.html, but if you want to check whether the user is authenticated to see specific contents e.g. the 'Admin Login', you can use include_once('Authentication.php') and initiate a class from this file, e.g. <?php $Auth = new Auth_Handler; ?> This will make the Auth class also available in the index.php or any other file you want to include this class. If you want to pass the authentication class' return value to another file e.g. 'register.php' you can use the SESSION or any other Cache. Passing whole objects is not recommend due to their size. Including and initiating the wanted classes at the beginning of files is much better. And passing the returns by SESSION uses less space.

It really depends one which framework or API you want to use, or what project you want to create.

Edited: Here you can see how i mean 'plug into one' "Link to a explaining picture ;)"

daemonfire300