LoginSignup
1
0

More than 1 year has passed since last update.

PHPの構文省略形まとめ

Last updated at Posted at 2022-08-11

うっすっす。豚野郎です

今回はPHPの省略構文形を書いていこうと思います。
前から知ってはいるんですけど、たまに読んでて「ん?」ってなったりすることがあるので
ここでまとめておこうと思います。

・バージョン:PHP 7.4.29

1. echo

普通のechoの書き方は以下の様な形です。

echo.php
<?php
    echo 'テストです。';

結果

テストです。

PHP タグの終了タグ ?> は省略することもできます。

echo.php
<?php
    echo 'テストです。';

結果

テストです。

公式でも省略が推奨されているみたいですね。

また、省略構文形を使うと以下のようにも書けます。

echo.php
<?='テストです。'?>

結果

テストです。

主にhtml内にPHPを埋め込む時に使われる記法です。

2. if文

①. コロンを使う方法

if.php
<?php
$test = 'test';

if ($test === 'test') :
    echo 'test';
else :
    echo '違うよ';
endif;

結果

test

htmlに埋め込む時は以下の様な書き方もできます。

if.php
<?php $test = 'test'; ?>
<?php if ($test === 'test') : ?>
    <?=$test?>
<?php else : ?>
    <?='違うよ'?>
<?php endif; ?>

結果

test

②. 三項演算子
以下の様な書き方です。

(条件式) ? (真式) : (偽式);
if.php
<?php
    $test = 'test';
    $result = ($test === 'test') ? 'test' : '違うよ';
    echo $result;

結果

test

条件式の()は省略ができます。

if.php
<?php
    $test = 'test';
    $result = $test === 'test' ? 'test' : '違うよ';
    echo $result;

結果

test

③. {}省略

if.php
<?php
    $test = 'test';
    if ($test === 'test')
        echo 'test';
    elseif($test === 'test' ||$test === 'aaa')
        echo '違うよ';

結果

test

3. 参考

ありがとうございました。
https://agohack.com/php-omitting/

1
0
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0