dreftymac dreftymac - 6 months ago 11
PHP Question

Ruby addict looking for PHP subexpressions in strings

Assume color = "orange";

Ruby:

puts("My favorite color is #{color.downcase() + 'ish'} -- at least for now.");


PHP:

print("My favorite color is {strtolower( $color ) + 'ish'} -- at least for now.");


The PHP version does not work like I would like it to. I'm not looking for any language wars, I just want to know if anyone knows of a way to get PHP to be more like Ruby in this specific regard.

Can anyone help a Ruby addict adjust to his routine visits to PHP-land? Is there an 'act-like-ruby' module somewhere out there? This is starting to hurt.

Answer

You can't call plain functions inside strings like that, but you can coax the parser into doing strange things:

<?php
print "{$a->b()}"; // Works

//Parse error: syntax error, unexpected '(' in Command line code on line 1
print "${time()}";

print "${$a=time()} $a"; // Also works: prints "1234380996"
?>

As long as it sees a valid variable at the start, it'll go ahead and interpolate an entire statement without complaining.

For those who were wondering, yes, this works too...

<?php
print "${$a or print shell_exec('ls')}";
?>