PHP 对象索引作为字符串?

标签 php arrays string object

有没有办法通过使用对象的名称作为字符串来访问对象的成员?

当我声明一个数组时...

$array = array();
$array['description_en']="hello";
$array['description_fr']="bonjour";

然后我像这样访问成员:

$lang="en"; //just to show my purpose. it will be dynamic
$description = $array['description_'.$lang];

我可以对对象做同样的事情吗?

例如:

$obj->description_en="hello";
$obj->description_fr="bonjour";

如何访问$obj->description_.$lang

最佳答案

class test
{
    public $description_en = 'english';
}

$obj = new test();
$lang = 'en';
echo $obj->{"description_".$lang}; // echo's "english"

可以查看更多可变变量的例子here .

关于PHP 对象索引作为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17947715/

相关文章:

php - 使用 PHP DOMDocument 解析脏 html 代码有困难

php - 如何获取php对象的第一个元素值

php - htmlspecialchars 导致文本消失

python - 根据多个范围从数组中检索间隔

c# - 如何在没有循环的情况下在 c# 中初始化类的 'NotNull' 数组?

c - 如何编写一个原型(prototype)为 'void convertstring(char *)' 的函数,在 C 中将小写字母转换为大写字母?

java字符串到日期时间的转换问题

php - 使用 PHP 进行即时搜索

ruby-on-rails - Ruby ActiveSupport 数组拆分与字符串拆分

string - 选择对象表达式作为字符串