Page 1 of 1

Passing objects between php files

Posted: Thu Jul 03, 2008 10:53 pm
by lilylily
Hi,
How do I pass objects between php files? I've tried using $_GLOBALS, $GLOBAL, $_REQUEST and can't get it to work. I'm basically trying to pass mysql results to another php file...example psuedo-code below:

//in myClass.php
class myClass
{
function search() {
$sql = "SELECT * FROM myTable ";

$result = mysql_query($sql) or die (mysql_error());

$GLOBALS['results'] = $result;
$GLOBALS['myclass'] = $this;
$GLOBALS['test'] = 2;

header("Location: search_results.php");
}
}

//in search_results.php
echo $GLOBALS['test']; //echos empty string, when it should echo 2
$myclass = $GLOBALS['myclass'];
$myclass->search(); //error saying that $myclass is not an object

Any help is appreciated.

Thanks.

Re: Passing objects between php files

Posted: Fri Jul 04, 2008 1:13 am
by jaoudestudios
No offence, but I think you need to go back to basics!

You are using the class in the wrong way.

on the search_results page you should have something like...

Code: Select all

$myclass = new myclass();
$myclass->search();
If you have a search form on the previous page then you would send the info in a get or a post and input it into the class on the search_results page and use the code above and send the GET or POST variables into the class. You might be able to shorten the code (depending on what you are doing, as at the moment there is no search it just lists all the results) but using the __construct function in the class.

But dont worry we have all been there, it is just the learning curve.

Re: Passing objects between php files

Posted: Fri Jul 04, 2008 8:06 pm
by lilylily
Thanks. I am new to php.

The reason I wrote
$myclass = $GLOBALS['myclass'] as oppose to
$myclass = new myclass(); was because I didn't want to create a new instance of the myclass object; what I really want to do is get a reference to the object from the previous page since that object has the results I need (creating a new instance would basically clear the member fields?)....I'm probably not explaining myself too clearly...basically what I want to implement is this:

1. User enters set of search criteria into a form on page1.php, I then grab results from mysql
2. I want to display results (from mysql) on page2.php

What is the best way to do this? I'm open to any suggestion. Thanks for all your help.

Re: Passing objects between php files

Posted: Fri Jul 04, 2008 8:57 pm
by lilylily
I re-read your post and understand it now. I got it working. Thanks!