1

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};
eroteev
  • 620
  • 1
  • 7
  • 17

3 Answers3

2

This should work:

$result = $myModel->fetchAll($query)->current();
echo 'Your name is '.$result->{'name_'.$language};
Godwin
  • 9,739
  • 6
  • 40
  • 58
  • Cheers Godwin! It is working! Please would you tell me where this behavior is documented. How can I search for it? Does it have a name? Thanks a lot! – eroteev Nov 23 '11 at 07:23
  • Fairly sure it's usually called a dynamic property but I can't find any official documentation out there (although I'm sure it is). – Godwin Nov 23 '11 at 07:34
  • It's called variable variables: http://php.net/manual/en/language.variables.variable.php – Radek Benkel Nov 24 '11 at 07:26
1

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();

Radek Benkel
  • 8,278
  • 3
  • 32
  • 41
0

Try this:

$result->{"name_$language"}
dfsq
  • 191,768
  • 25
  • 236
  • 258