0

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.

2 Answers 2

3

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?

Sign up to request clarification or add additional context in comments.

1 Comment

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. ;)
0

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, or pass the variable to the function (which is generally preferable, as globals are bad). 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 ...
   }

?

2 Comments

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 weird! Then what @deceze suggests is the only explanation I can think of.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.