Gabo Gabo - 3 years ago 50
PHP Question

php: access public variable in a class which is defined in an other class

I have a config.php:

<?php
class GConfig {
public $DbServer = "localhost";
public $DbName = "golee";
public $DbUser = "golee";
public $DbPassword = "SASASASASAS";
public $CharSet = "UTF8";
}
?>


I have an other file called functions.php:

<?php
class DataBase {

function opendb() {
$node = mysqli_connect($config->DbServer, $config->DbUser, $config->DbPassword);
mysqli_select_db($node, $config->DbName);
mysqli_set_charset($node, "$config->CharSet");
return $node;
}

}
?>


These two files are included in index.php:

<?php
include "config.php";

$config = new GConfig;
echo $config->DbServer;

include "functions.php";
$datab = new DataBase();
$dbnode = $datab->opendb();

?>


The "echo $config->DbServer;" display the value: localhost which is OK so I can access to the variables defined in GConfig class even if I write the "echo $config->DbServer;" at the beginning of functions.php.

But I get an error "Undefined variable: config in functions.php on line 5".

I also tried to extend the GConfig class like this but doesn't work:

class DataBase extends GConfig {
function opendb() {
$node = mysqli_connect($config->DbServer, $config->DbUser, $config->DbPassword);
mysqli_select_db($node, $config->DbName);
mysqli_set_charset($node, "$config->CharSet");
return $node;
}

}


My question is how can I access to the variables within the DataBase class which are defined in the GConfig class?
I already read many questions and answers in the similar topic but non of them described the same problem I have.

The question is not that if a variable defined in one file is available in an other file.

Answer Source

just create new object in functions.php file then you can access this class in your function.

<?php
class DataBase {

   function opendb() {
       $new_connect = new GConfig();
       $node = mysqli_connect($new_connect->DbServer, $new_connect->DbUser, $new_connect->DbPassword);
       mysqli_select_db($node, $new_connect->DbName);
       mysqli_set_charset($node, "$new_connect->CharSet");
       return $node;
   }

}
?>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download