Page 1 of 1

Sharing PHP globals between scripts?

Posted: Tue Jun 01, 2010 12:01 pm
by dukesdemise
I'm learning PHP now, which should be obvious when you read my question below. :D

What I would like to do is share a global variable between scripts, without using a $_SESSION variable. Is this possible? My eventual goal is to assign a PDO database handle to this variable in order to be able to use it between scripts within the same application (using a $_SESSION variable causes an exception). In J2EE you would simply assign the variable to the application context.

Here is some sample code with two different scripts that is not doing what I had hoped it would.

What gets printed out is: [text]The message is: [][/text]

What I would like to have printed out is: [text]The message is: [hello world][/text]

Here is the code:

Code: Select all

<?php
// create_message.php
$hello = "hello world";
header ("Location: http://localhost/read_message.php");
exit();
?>

<?php
// read_message.php
global $hello;
echo "The message is: [$hello]";
?>

Re: Sharing PHP globals between scripts?

Posted: Tue Jun 01, 2010 12:24 pm
by AbraCadaver
You either need to pass it along using get or post or use a session. What is wrong with using a session???

Re: Sharing PHP globals between scripts?

Posted: Tue Jun 01, 2010 12:28 pm
by AbraCadaver
Also, there's no reason to pass your PDO object, just create one when needed.

Re: Sharing PHP globals between scripts?

Posted: Tue Jun 01, 2010 12:40 pm
by dukesdemise
I could create the PDO object in each individual script, but I'm thinking that would not be very efficient and would hurt the performance of the application. Why create it over & over if I could create it once & make it available to the entire application?

Using a session object yields the following exception:

[text]Fatal error: Exception thrown without a stack frame in Unknown on line 0[/text]

Here is the code:

Code: Select all

<?php
   session_start();
   try {
      $mysql_root_password = '';

      $dsn = 'mysql:host=localhost;dbname=mysql';
      $dbh = new PDO ($dsn, 'root', $mysql_root_password);
      $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, TRUE);
      $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

      $_SESSION['dbh'] = $dbh; // <= this line is NOT liked, and will throw an exception

      $sql = "SELECT * FROM db";
      $stmt = $dbh->prepare($sql);
      $stmt->setFetchMode(PDO::FETCH_OBJ);
      $stmt->execute();
      $results = $stmt->fetchAll();
   }
   catch (Exception $e) {
      echo 'Failed: ' . $e->getMessage();
   }

   exit;
?>

Re: Sharing PHP globals between scripts?

Posted: Tue Jun 01, 2010 12:54 pm
by AbraCadaver
A PDO object probably contains a resource and resources can't be serialized / saved in the session.

Re: Sharing PHP globals between scripts?

Posted: Tue Jun 01, 2010 6:08 pm
by dukesdemise
Thank you for your help.