I’m wondering if there is a shorter way of inserting text in PHP than
<?php
$city = "London";
?>
This website is a funky guide to <?php print $city; ?>!!!
For example, using ruby on rails, I could set
city = 'London'
somewhere in the code, and in my .erb file I could do
This website is a funky guide to <%= city %>!!!
I did read somewhere that {$city} could be used, but I tried it and it didn’t. So is there a shorter form than <?php print $var; ?> ?
You could use
short_open_tag, which have to be enabled in your configuration, but that’s not considered as a good practice, as it only works if those are enabled — and they are not always (maybe not even by default)Using long tags and echo/print might be longer, yes… But I would recommend using those, and not short tags.
Also note that you might need to escape your data, when it comes from an un-trusted source and/or might contain HTML you don’t want to get injected in the page, to avoid injections of HTML/JS (see htmlspecialchars) :
EDIT after the comments, to add couple of things about
short_open_tag:Why are short open tags considered (at least by me ^^ ) bad practice ?
First of all, after some checking, they are not enabled by default :
For PHP 5.3 :
Disabled by default in either “
development” or “production” settings.For PHP 5.2.10 (most recent version of PHP 5.2) :
Disabled by default in the “
recommended” settingsConsidering these default settings are sometimes (often ?) kept by hosting services, it is dangerous to rely on
short_open_tagbeing activated.(I have myself run into problem with those being disabled… And when you are not admin of the server and don’t have required privilegies to modify that, it’s not fun ^^ )
If you want some numbers, you can take a look at Quick survery:
short_open_tagsupport on or off by default?(Not a scientific proof — but show it could be dangerous to use those for an application you’d release to the public)
Like you said, those, when activated, conflict with XML declaration — means you have to use something like this :
Considering short open tags exists, and might be activated on the server you’ll use, you should probable not use
<?xmlever, though ; too bad 🙁Actually, reading through the php.ini-recommended of PHP 5.2.10 :
The one from PHP 6 is even more interesting :
(Might be the same in PHP 5.3 ; didn’t check)
There have been rumors short open tags could be removed from PHP 6 ; considering the portion of php.ini I just posted, it probably won’t… but, still…
To give an argument pointing to the other direction (I’ve gotta be honest, after all) : using short open tags for template files (only) is something that is often done in Zend Framework’s examples that use template files :
(source)
On the contrary, for
.phpfiles :(source)
I hope those informations are useful, and bring some kind of answer to your comment 🙂