PHP タグ

PHP はファイルを解析して開始タグと終了タグ (<?php?>) を探します。 タグが見つかると、PHP はコードの実行を開始したり終了したりします。 このような仕組みにより、PHP を他のあらゆる形式のドキュメント中に 埋め込むことができるのです。つまり、開始タグと終了タグで囲まれている 箇所以外のすべての部分は、PHP パーサに無視されます。

PHP では、短い形式のechoタグ <?= も使えます。 これは、より冗長な <?php echo を短くしたものです。

例1 PHP の開始タグと終了タグ

1.  <?php echo 'XHTMLまたはXMLドキュメントの中でPHPコードを扱いたい場合は、このタグを使いましょう'?>

2.  短い形式の echo タグを使って <?= 'この文字列を表示' ?> とすることもできます。
    これは <?php echo 'この文字列を表示' ?> と同じ意味になります。

3.  <? echo 'このコードは短縮型のタグに囲まれていますが、'.
            'short_open_tag が有効な場合にしか動作しません'; ?>

短縮型のタグ(例 3.)はデフォルトで有効ですが、 php.ini 設定ファイルのディレクティブ short_open_tag で無効にすることもできますし、 --disable-short-tags オプション付きで configure した場合は、 デフォルトで無効にすることも出来ます。

注意:

短縮形のタグは無効にすることができるので、 互換性を最大限保つために、通常のタグ (<?php ?> and <?= ?>) を使うことを推奨します。

ファイルが PHP コードのみを含む場合は、ファイルの最後の終了タグは省略するのがおすすめです。 終了タグの後に余分な空白や改行があると、予期せぬ挙動を引き起こす場合があるからです。 余分な空白や改行のせいで PHP が出力バッファリングを開始し、その時点の内容を意図せず出力してしまうことになります。

<?php
echo "みなさん、こんにちは";

// ... いろんなコードたち

echo "最後のごあいさつ";

// PHP 終了タグを書かずに、ここでスクリプトを終わります。

add a note add a note

User Contributed Notes 2 notes

up
-4
admin at bharatt dot com dot np
2 years ago
You may want to know that removing semicolon is optional sometime but need to know the condition when it can be removed and when it can't be.
-------------------------------------------------------------------------
// Example 1: PHP script with closing tag at the end.
<?php

// php code

// you can remove semicolon
mysqli_close( $db )
?>

// Example 2: PHP script without closing tag at the end.
<?php

// php code

// you can't remove semicolon
mysqli_close( $db )

-----------------------------------------------------------------------
up
-64
anisgazig at gmail dot com
3 years ago
Everything inside a pair of opening and closing tag is interpreted by php parser. Php introduced three types of opening and closing tag.
1.Standard tags
<?php ?>
2.Short echo tag
<?=  ?>
here, <?=  is equivalent meaning of "<?php echo"
3.Short tag
<?   ?>

Standard tag and short echo tag are alwayes available.
But short tag can be disabled either via the short_open_tag php.ini configuration file directive, or are disabled by default if PHP is built with the --disable-short-tags configuration.

If a file contains only PHP code, it is preferable to omit the PHP closing tag at the end of the file.
This prevents accidental whitespace or new lines being added after the PHP closing tag
To Top