动态访问数组类型的对象属性
我正在构建一个用于国际化的语言类,我想动态访问属性(给出字符串名称),但我不知道在处理数组时如何做到这一点(这只是一个例子):
class Language {
public static $languages_cache = array();
public $index_header_title;
public $index = array(
"header" => array(
"title" => NULL
)
);
}
现在我添加像这样的语言:
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 _($member, $lang)
{
if (!property_exists('Language', $member))
return "";
return Language::$languages_cache[$lang]->$member;
}
所以,输出成员:
echo _('index_header_title', "en"); //works
echo _('index["header"]["title"]', "en"); //does not work
我需要一种动态访问数组的方法..通过 __set() 函数用于公共和私有数组。
谢谢你!
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 way for accessing arrays dynamically.. for public and private via __set() function.
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以尝试使用分隔符标志,以便可以解析数组路径。唯一的问题是您混合了属性和数组,这可能会使事情变得复杂。
您可以这样调用您的函数:
您的函数将解析路径并返回正确的值。看一下 Kohana 3.0 中的数组助手。它具有您想要的确切功能。 http://kohanaframework.org/guide/api/Arr#path
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:
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