PHP's magic methods question
I store all variables settings for some project in a class named Ini
. Variables are stored in group of arrays. For example, I have several arrays - one for 'database' related stuff, another for 'debug' related stuff and so on.
So to access for example some settings in my code i would type:
$ini = new Ini();
echo $ini->database['user'];
echo $ini->debug['mode'];
I don't like my way of doing this. I would like to access variables stored inside Ini
class like this:
$ini->database->user;
or
$ini->debug->mode;
The problem is that i am referencing non existing object inside another object. And i found no way to catch such ca开发者_如何学编程ll and return values stored in original Ini
object (via PHP __get()
method)
Would appreciate some help finding solution to my problem.
Just create objects of the standard class:
$a = new stdClass;
$a->database = new stdClass;
$a->database->host = 'localhost';
echo $a->database->host;
as an optional choice, you can take your existing arrays and cast them to objects and access with the same syntax:
$a = new stdClass;
$a->database = new stdClass;
$a->database = (object)array('host' => 'localhost');
echo $a->database->host;
Instead of arrays you could use stdClass objects.
stdClass is a generic class that you can use as a container of your data, and than you get get the values using the object syntax.
Example:
class Ini() {
public $database;
public function __construct() {
$this->database = new stdClass();
$this->database->user = 'foo';
}
}
and then
$ini = new Ini();
echo $ini->database->user; //outputs 'foo'
Have a look at Zend_Config. It does exactly what you're after and supports various formats
- PHP array
- .ini file
- XML
What you need to do is convert your array to object. However, doing the conversion from array to object just for the sake of being able to access the property via -> instead of associative index is - well, silly if you ask me.
精彩评论