Frage

I was going through some old code that I'd been using, and knew worked because it was still functioning. I was, however, confused when I found I'd written a <?, but not <?PHP. And yet, the code after that still worked. Is this defined? Is this supposed to work like this? Have I been writing slightly more code than I could be? It feels dirty to leave off the PHP, but if it's okay, I might as well, right?


Sandbox: http://sandbox.onlinephpfunctions.com/code/69b81a2f45927d3feb52af012521480e1ba01edd

War es hilfreich?

Lösung

From the PHP manual:

When PHP parses a file, it looks for opening and closing tags, which are <?php and ?>, which tells PHP to start and stop interpreting the code between them. Parsing in this manner allows PHP to be embedded in all sorts of different documents, as everything outside of a pair of opening and closing tags is ignored by the PHP parser.

PHP also allows for short open tags <? and ?> (which are discouraged because they are only available if enabled with short_open_tag php.ini configuration file directive, or if PHP was configured with the --enable-short-tags option.

Andere Tipps

Its depend on server configuration. If server has enabled short_open_tag

short_open_tag=On

in php.ini file, PHP will allow for short tags.

Note: PHP not recommend to use short tags.

Good Discussion Link

If you can use only <?php ?> or you can use both <? ?> and <?php ?> depends on server configuration.

Enabling usage of <? ?> might cause problems in some applications. Imagine, that you have this code in your index.php or index.phtml file:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
    <head></head>
    <body></body>
</html>

With enabled <? ?> you would run into error, because <? is part of xml definition here:

<?xml version="1.0" encoding="UTF-8"?>

Therefore you would have to disable usage of <? ?> in server configuration or you would have to use some workaround.

However, usage of <? ?> makes files where you combine HTML and PHP code more readable. <?= $var ?> is more readable and shorter than <?php echo $var ?>.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top