lift_spindle's avatar

string interpolation or .

in python I use f strings all the time. in php i use the . all the time, but php can string interpolate if you use double quotes. maybe that's why pint tells me to use single quotes...

any way. what do you use?

0 likes
4 replies
martinbean's avatar

any way. what do you use?

C: Other. I personally use Laravel’s __() helper for formatting strings with placeholders. For example:

$title = __('Rent :video from :channel.', [
    'video' => 'Test Video Name',
    'channel' => 'Test Channel Name',
]);
Snapey's avatar

interesting. I always reach for sprintf()

$title = sprintf('Rent %s from %s.', 
     'Test Video Name',
     'Test Channel Name',
);

Particularly when the string need to contain data from functions, instead of using a temporary variable.

martinbean's avatar
Level 80

@snapey I used to use sprintf a lot, but feel the __() helper has the benefit of named placeholders rather than just %s and the like. You can still use results from functions if you really wanted to:

$title = __('Rent :video from :channel.', [
    'video' => function_to_get_video_name(),
    'channel' => function_to_get_channel_name(),
]);
hinlocaesar-75309181's avatar

So my rule of thumb:

Python → f-strings

PHP → single quotes + .

Double quotes in PHP only when interpolation is actually worth it

Consistency and readability > clever syntax.

Please or to participate in this conversation.