RE: [PHP] how call a variable in a text
| From: | Andrea Giammarchi | Date: | Thu, 22 Oct 2009 11:18:57 +0000 |
| Subject: | RE: [PHP] how call a variable in a text | ||
| References: | 1 2 3 4 5 6 7 8 9 10 11 12 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-299191@lists.php.net to get a copy of this message | ||
> I don't think it is about readability:
>
> $arr[3] = 'test';
> $test = 3;
>
> //This prints "$test"
> echo "This doesn't work: $$arr[3]";
>
> //This prints 3
> echo "This works: ${$arr[3]}";
>
> Using the same type way as before in this thread.
Above example is a classic one where readability and maintainability deal well together.
First of all everything works as expected but obviously you need to know what you need.
It is ambiguous to write $$arr[3] ... what do you expect?
Did you mean the variable derived by $arr[3]?
echo "This works: {$$arr[3]}";
since curly brackets make the meaning of the expression explicit, it will be 3 indeed.
What is the less ambiguous, readable, easy to maintain, way to obtain that result?
echo "This works: {${$arr[3]}}";
If our aim is to get the variable with name equal to the value of $arr[3]
Can you see now why I am talking about good practice? Zero ambiguity, and that's how I like to
code
Regards
_________________________________________________________________
Windows Live: Friends get your Flickr, Yelp, and Digg updates when they e-mail you.
http://www.microsoft.com/middleeast/windows/windowslive/see-it-in-action/social-network-basics.aspx?ocid=PID23461::T:WLMTAGL:ON:WL:en-xm:SI_SB_3:092010