0
0

変数のスコープ JavaScriptとPHPの違い

Last updated at Posted at 2023-11-25

JavaScript(letとconst)

  1. {}でエリアが形成される
  2. 内のエリアで、外のエリアで宣言された変数を扱うことはできる
  3. 外のエリアで、内のエリアで宣言された変数を扱うことはできない
  4. 外の複数のエリアで同名の変数が宣言されているとき、最も近いものが扱われる

2. 内のエリアで、外のエリアで宣言された変数を扱うことはできる

test.js
const a = 'aaa'
{
    console.log(a) // aaa
}

3. 外のエリアで、内のエリアで宣言された変数を扱うことはできない

test.js
{
    const b = 'bbb'
}
console.log(b) // ReferenceError: b is not defined

4. 外の複数のエリアで同名の変数が宣言されているとき、最も近いものが扱われる

test.js
const a = 'a1', b = 'b1'
{
    const a = 'a2'
    console.log(a, b) // a2 b1
    {
        console.log(a, b) // a2 b1
    }
}

PHP

functionの内から外で宣言された変数を扱うことはできない。外から内もできない。

test.php
$x = 'xxx';
function f () {
    echo $x; // Undefined variable $x
    $z = 'zzz';
}
f();
echo $z; // Undefined variable $z

まとめ

  • JSではとにかく"{}"(ifやfor、関数(関数宣言、関数式、アロー関数いずれでも)など)でエリアが形成される
  • PHPではfunctionでエリアが形成される。ifやforではエリアが形成されないので、内から外の、外から内の変数を扱うことができる
0
0
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
0
0