This is an example of how the __construct() method can be used to set variable values from another file.
Create a file called config.php, then add the following:
<?php
$sql['host'] = ‘host’;
$sql['name'] = ‘name’;
$sql['user'] = ‘user’;
$sql['pass'] = ‘pass’;
?>
Now create a file named simClass.php, add:
<?php
include ‘config.php’;
class sqlMngr {
public $conf = array();
public function __construct() {
global $sql; // I forgot this originally.
$conf['host'] = $sql['host'];
$conf['name'] = $sql['name'];
$conf['user'] = $sql['user'];
$conf['pass'] = $sql['pass'];
}
}
$obj = new sqlMngr();
print_r($obj->conf);
?>




2 Comments
hey aren’t you ignoring scope with this example? you should use the global keyword on $sql inside of __construct() before that code will work.
I made the changes accordingly, thank you for pointing that out.