gpt4 book ai didi

PHP 对象索引作为字符串?

转载 作者:行者123 更新时间:2023-12-02 21:54:46 27 4
gpt4 key购买 nike

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

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

$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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com