Re: how call a variable in a text

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Thu, Oct 22, 2009 at 8:40 AM, Thodoris <tgol@xxxxxxxxxx> wrote:

>
>
>>
>>> 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?]
>>
>>
>
> No I don't think it is. It produces "$test" and if this is what you need
> echo it works nice :-) .
>
>  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
>>
>>
>>
>
> Although I totally  agree with the way of thinking and it is my style as
> well.
>
> But I though that the point of the thread was to present ways of putting
> vars inside strings...
>
> --
> Thodoris
>
>
PHP knows that before $ and {} there is a variable name.... so, this is
completely correct for PHP

<?php // tested on PHP 5.2.6, is this correct on PHP <= 5 ?

$name = 'Martin';
$var = 'name';

echo "$name {$name} ${name} ${ 'name' } ${$var} {$$var} ${${ 'var' }}"
,PHP_EOL;
// am I missing any other way here?

// this is non-sense, but funny :)
$a = 'b';
$b = 'c';
$c = 'd';
$d = 'e';
$e = 'a';

$swap = 'a';

for($i=0,$e=rand(1, 100); $i<$e; ++$i)
    $swap = ${ $swap };

echo $swap, PHP_EOL;

I feel ${ $var } safer for developers than $$var because I feel it more
readable.
$$var can be interpreted by a typo for somebody, while with ${ $var } there
is no doubt what was the coder intent.


-- 
Martin Scotta

[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux