Accessing object's properties like if the objects were arrays

跟風遠走 提交于 2019-12-11 10:26:51

问题


Is it possible to access object's properties, when you don't know just how their names will be written?

My problem is that when a query returns Zend_Db_Table_Rowset_Abstract object, there are some fields with names like "name_fr", "name_en", "name_au". I want to access either of them according to the current language used in the application. To achieve this I write the code this way:

$result = $myModel->fetchAll($query)->current();
$row = $result->toArray();
echo 'Your name is '.$row['name_'.$language];

This is very annoying. Is it possible to write a code like this for example:

$result = $myModel->fetchAll($query)->current();
echo 'Your name is '.$result->name_{$language};

回答1:


This should work:

$result = $myModel->fetchAll($query)->current();
echo 'Your name is '.$result->{'name_'.$language};



回答2:


When you use Zend_Db_Table and fetchAll()->current(), type of returned object is Zend_Db_Table_Row, which inherits from Zend_Db_Table_Row_Abstract. Zend_Db_Table_Row_Abstract implements ArrayAccess(manual) interface, which means you can refer to object properties using array key notation.

So, syntax:

'Your name is '.$row['name_'.$language];

should work without using toArray();




回答3:


Try this:

$result->{"name_$language"}


来源:https://stackoverflow.com/questions/8238380/accessing-objects-properties-like-if-the-objects-were-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!