LoginSignup
1
1

More than 5 years have passed since last update.

波括弧(brace{})を使った文字列リテラル"外"での変数展開(変数のパース)について

Last updated at Posted at 2017-05-15

:bow: お詫び

PhpStormでシングル・ダブルクォーテーションを変換するPHP 1Up! プラグイン - Qiita

image.png

image.png

適切に分けることもできる。

適切に分かれません。
よく見ると背景色が変わって警告が出ている。

結論

そもそも${hoge}という書き方はない。…多分。
ただし、文字列リテラル内ではセーフ。

文字列リテラル外だと、

{$hoge}
はシンタックスエラー。
${hoge}
はhogeのみが解釈され、定数として扱われ、
$定数の値
という変数を探す。

コード


<?php

ini_set('display_error', 'On');
error_reporting(-1);

$hr = function() {
    static $i = 1;
    echo "\n\n" . $i++ . "\n-----\n";
};


$a = 'Z';

$hr();

echo "cb$a";

$hr();

echo "cb{$a}a";

$hr();

echo "cb${a}a";

$hr();

echo $a;

$hr();

echo ${a};

$hr();

//echo {$a}; //PHP Parse error:  syntax error, unexpected 'echo' (T_ECHO) in /tmp/brace.php on line 36



一部ネタバレしているが、
実行結果

1
-----
cbZ

2
-----
cbZa

3
-----
cbZa

4
-----
Z

5
-----
PHP Notice:  Use of undefined constant a - assumed 'a' in /tmp/brace.php on line 32
Z

6
-----


${a}aが定数扱いとなり、未定義定数は変数名として扱われるPHPの親切機能により$aと解釈される?
$$a$Zにはならないもよう?





ini_set('display_error', 'On');
error_reporting(-1);

$a = 'Z';

define("a", '定数だよー!');

echo "\n";

echo ${a};

echo "\n";

PHP Notice:  Undefined variable: 定数だよー! in /tmp/const.php on line 12

んんん??

<?php

ini_set('display_error', 'On');
error_reporting(-1);

$a = 'Z';

define("a", '定数だよー!');

$定数だよー = 'なんだよー!';

echo "\n";

echo ${a};

echo "\n";


なんだよー!

なんだよー!
どうして最初のコードでUndefined variableが出ないのだ!
冗長だからか!
そもそも間違った書き方だから知らん!

1
1
1

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