Why does this return an array instead of an object and how can I return an object?
Class MyClass {
private $filename = '...';
private $_ini_array;
public function __construct() {
// Get the config file data
$ini_array = parse_ini_file( $filename, true );
$this->_ini_array = $ini_array;
}
public function __get( $param ) {
return $this->_ini_array[ $param ];
}
}
called by...
$c = new MyClass();
var_dump( $c->db_pgsql );
returns...
array(6) {
["data"]=>
string(4) "test"
...
and casting by...
return (object) $this->_ini_array;
returns...
object(stdClass)#2 (6) {
["data"]=>
string(4) "test"
...
while I wish to return...
object(MyClass)#2 (6) {
["data"]=>
string(4) "test"
...
Many Thanks!
Update. Solved.
I ended up writing the following class that pretty much accomplishes my goals. Please comment if you see any bad habits, sloppy code, etc.
class Config {
private $config_filename = '../include/config.ini';
public function __construct( array $array=null ){
if ( $array ) {
foreach ( $array as $key => $val ) {
$this->$key = $val;
}
} else {
$ini_array = parse_ini_file( $this->config_filename, true );
foreach( $ini_array as $key => $val ){
$this->$key = new self( $val );
}
}
}
public function __get( $param ) {
return $this->$param;
}
}
Which, with my particular test config file, produces an object that looks like...
VarDump: object(Config)#1 (3) {
["config_filename:private"]=>
string(21) "../include/config.ini"
["heading1"]=>
object(Config)#2 (3) {
["config_filename:private"]=>
string(21) "../include/config.ini"
["str1"]=>
string(4) "test"
["str2"]=>
string(5) "test2"
}
["heading2"]=>
object(Config)#3 (2) {
["config_filename:private"]=>
string(21) "../include/config.ini"
["str1"]=>
string(9) "testagain"
}
}
I would have preferred not to have recursively duplicated the ["config_filename:private"] property like it did. But I couldn't conceive a way around it. So if you know of a workaround then I'd appreciate a comment.
Thanks for all the help to get me in the right direction.
_ini_array[db_pgsql]get set?