开发者

Accessing object properties of type array dynamically

I am building a Language class for internationalization, and I would like to access the properties dynamically (giving the string name), but I don't know how to do it when dealing with arrays (this is just an example):

class Language {

    public static $languages_cache = array();

    public $index_header_title;

    public $index = array(
        "header" => array(
            "title" => NULL
        )
    );
}

Now I add languages like this:

Language::$languages_cache["en"] = new Language();
Language::$languages_cache["en"]->index_header_title = "Welcome!"; //setting variable
Language::$languages_cache["en"]->index["header"]["title"] = "Welcome!"; //setting array

Function for accessing members dynamically:

function _($member, $lang)
{
    if (!property_exists('Language', $member))
        return "";

    return Language::$languages_cache[$lang]->$member;
}

So, outputting members:

echo _('index_header_title', "en"); //works
echo _('index["header"]["title"]', "en"); //does not work

I would need a wa开发者_如何学运维y for accessing arrays dynamically.. for public and private via __set() function.

Thank you!


You could try using a separator flag so that you can parse the array path. The only problem is you are mixing you properties and arrays so that might complicate things.

You would call your function like this:

echo _('index.header.title', "en");

And your function would parse the path and return the correct value. Take a look at the array helper in Kohana 3.0. It has the exact function that you want. http://kohanaframework.org/guide/api/Arr#path

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜