php appending string to stdClass object
Asked Answered
D

3

5

I'm pulling records from database, and I have a filed called content_fr the _fr is being dynamicaly created based on a site language.

Getting all records from the table gives me of course content_fr field. What I need to do is manually assign the suffix in this case _fr if I try to concatenate $row->content.'_fr' I get the error Notice: Undefined property: stdClass::$content, which makes sense since $content does not exist, but $content_fr does. Using standard arrays I was able to do it like $row['content_fr'], and worked fine, but now using stdClass I'm getting an error.

How can I convert $row->content.'_fr' into one string, so that php sees it as $row->content_fr ?

Diu answered 27/11, 2011 at 19:37 Comment(1)
Dunno how your models are set, but you should use getters for columns and there you would implement the localization-to-column logic (injecting the language into the model, ofc).Chairborne
O
16

Try it like this :

$row -> {'content_' . $language}; // assuming $language = 'fr'
October answered 27/11, 2011 at 19:48 Comment(0)
F
2

You can do it as follows:

$row->{'content_fr'};

EDIT: By the way, this question has been asked here many times. See previous threads such as this one: Accessing object's properties like if the objects were arrays.

Fi answered 27/11, 2011 at 19:43 Comment(5)
When downvoting, please leave a comment.Fi
$row->{'content_fr'} makes no sense as it is the same as $row->content_fr. The problem is the concatenation of strings into one property name. @Tom van der Woerdt 's solutions is what the OP is looking for.Mystify
I +1'd your answer cause it is what he needs, not sure why someone downvoted again.Comorin
@markus, It's quite different, I'm showing that the OP can access the property using a string value.Fi
@Comorin No, it's not what he needs. What he needs is Toms answer, as stated above.Mystify
C
0

Try something like this:

$lang = 'fr';
$property = 'content_' . $lang; // content_fr
$row->$property = 'something';
Comorin answered 27/11, 2011 at 19:43 Comment(2)
Yes the most I've ever written!Comorin
This is also a good alternative way to do this. Why do people keep downvoting when the answer is valid but perhaps just not the full code the OP needs?Fi

© 2022 - 2024 — McMap. All rights reserved.