Context
- PHP 5.3.x
Overview
After doing a code-review with an associate who uses both php and ruby routinely, a fun challenge came up on string interpolation in php compared to ruby.
Question
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.');
Challenge: can anyone specify a way to get the PHP version behave like Ruby?
Caveat
This challenge is intended as a fun exercise with the constraint of using only straight PHP. This is not intended for serious PHP projects. For serious PHP projects, the developer will want to consider addon libraries, such as TWIG.
You can’t call plain functions inside strings like that, but you can coax the parser into doing strange things:
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…