LoginSignup
1
1

More than 5 years have passed since last update.

PHP Manual 読書会(7回目)(制御構造1)

Posted at

PHPに慣れる為に週1ぐらいで更新していきます。PHP Manualを読んで実験して行きます。

前回:PHP Manual 読書会(6回目)(演算子#2)

制御構造に関する別の構文

PHPは、いくつかの制御構造、つまり、if、 while、for、 foreach、switch に関する別の構文を提供します。 各構造において開き波括弧をコロン(:)、閉じ波括弧をそれぞれ endif;,endwhile;, endfor;,endforeach;, endswitch;に変更するのが 別の構文の基本的な形式となります。

  • if
  • while
  • for
  • foreach
  • switch

これらは、通常の構文の他に別の構文を提供するようだ。

<?php

$a = 1;

?>

<?php if ($a == 1): ?>
ok
<?php endif; ?>

if .. endif; という形で囲む形で使用できる。

declare

declare 文は、あるコードブロックの中に 実行ディレクティブをセットするために使用されます。

現状使用出来るディレクティブは以下の3つ。

ticks

tickとはdeclareブロックの実行中にパーサが N個の低レベル tick 可能な文を実行するごとに 発生するイベントのこと
Nの値は declareブロックのディレクティブの箇所で ticks=Nのように 指定します。

<?php

declare(ticks=1);

function handler() {
    echo "tick\n";
}

register_tick_function('handler');

echo "hello\n";
echo "hello\n";
tick
hello
tick
hello
tick

encoding

スクリプトのエンコーディングをスクリプトごとに指定するには encoding ディレクティブを使用します。

<?php

declare(encoding='');

設定してないとwarningsがでるので注意。

strict_types

ファイル単位で厳密な型チェックを有効にすることもできます。 この場合は、宣言されたとおりの型でない限りは受け付けず、 TypeError をスローします。

<?php

declare(strict_types=1);

function num(int $num) {
    return $num;
}

echo num(1.1);
PHP Fatal error:  Uncaught TypeError: Argument 1 passed to num() must be of the type integer, float given, called

付けない場合は、以下

<?php

function num(int $num) {
    return $num;
}

echo num(1.1);
1

違う値になってしまうので、型チェックあった方が良いですね。

1
1
0

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
1