Jump to content

problem with include file for function


ltbaggz

Recommended Posts

I am trying to include a file that just defines some parameters for database access.  my setup is as follows
[code]
<?php
include_once("include/mysql_class.php");
include_once("include/db_info.php");

function go($year, $month)
{

$my_db = new mysql($db, $db_host, $db_pass, $db_user);
$name = $my_db->get_name();
echo $name;
$my_db->connect();
//there is more to the function but this is where the problem is

}
?>

[/code]
the variables, $db, $db_host, $db_pass, $db_user are defined in this file but it will not recognize them and prints nothing for $name, i use this same file in another places and the variables are accessed fine. the only difference is that this is a function but i cant see why that would matter.  any ideas?

Drew
Link to comment
https://forums.phpfreaks.com/topic/29729-problem-with-include-file-for-function/
Share on other sites

It's a scope problem.

Variables defined outside of a function are not visible inside of the function unless they are either declared as globals inside the function or are passed as parameters.

To set them as globals, do something like:
[code]<?php
function go($year, $month)
{
        global $dbm $db_host, $db_pass, $db_user;
$my_db = new mysql($db, $db_host, $db_pass, $db_user);
$name = $my_db->get_name();
echo $name;
$my_db->connect();
//there is more to the function but this is where the problem is

}
?>[/code]

To pass them as parameters:
[code]<?php
function go($year, $month, $db, $db_host, $db_pass, $db_user)
{

$my_db = new mysql($db, $db_host, $db_pass, $db_user);
$name = $my_db->get_name();
echo $name;
$my_db->connect();
//there is more to the function but this is where the problem is

}
?>[/code]

If you pass them by parameters, you will have to change any lines that call the function.

Ken

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.