Reputation: 6974
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.
Upvotes: 1
Views: 245
Reputation: 48897
Why does this return an array instead of an object[...]
The only thing I see setting $this->_ini_array
is the return value of parse_ini_file
, which returns an array (an array of arrays).
how can I return an object?
You'll need to iterate over the pertinent array and populate an object manually.
Upvotes: 2
Reputation: 19979
According to your code you are parsing an ini file, then returning an element of the resulting array. According to your calling code you are expecting some value to be returned using 'db_pgsql' as the key, which will be a string.
If you want an object you will have to instantiate an object then return it, something like:
class Bar
{
}
class Foo
{
public function __get($param)
{
return new $param();
}
}
$foo = new Foo();
var_dump($foo->Bar);
Upvotes: 0