tags:

views:

31

answers:

2

For years I have done something like this:

config.php

<?php

   $db = array("user" => "username", "pass" => "password");

functions.php

<?php
   require_once('config.php');
   function connectToDatabase() {
       $dbc = new PDO($dsn, $db['user'], $db['pass']);
       // Do some stuff ...
   }

I've just read the PHP manual and that SHOULDNT work, but for years it has. Are there any server configurations that allow that to work?

I've just coded a new script and getting errors. The $db array is not even initialized.

A: 

This should in fact never work, not even in older PHP versions nor with register_globals.

To import a global variable into a function, you need a global $varname; statement. The only exception are superglobals.

Are you 1000% sure it was not like this:

   function connectToDatabase() {
       require_once('config.php');
       $dbc = new PDO($dsn, $db['user'], $db['pass']);
       // Do some stuff ...
   }

?

Pekka
I'm just checking through some of my scripts and they contain my original example. I have a dedicated centos server that was configured by myself a while back. It's what I host all clients jobs on. I know it seems strange, and even impossible, but it's what I've been doing up until today when it had me stumped for over an hour because it wasnt working.
Jamie Redmond
@Jamie weird! Then what @deceze suggests is the only explanation I can think of.
Pekka
+2  A: 

Indeed, there are no variables in scope at the beginning of your connectToDatabase function. You should have gotten warnings about undeclared variables, too. Maybe it worked because of the configuration of your database installation that caused it use default usernames and passwords?

deceze
If this is in fact the explanation I hereby officially declare this technique to be called *programming by serendipity*, or, as @Pekka should understand, *mehr Glück als Verstand*. ;)
deceze