0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

PHP 関数スコープ ローカル、グローバル

Posted at

PHPの関数スコープについての基本

例)


<?php

$a =10;
$n = 100;


<?php
$a = 10;
$n = 100;

function change()
{
    print $GLOBALS['a'] . "\n";
    $GLOBALS['a'] = 25;
}
change(); //10
print $a . "\n"; //25

function change2()
{
    $n = 10;
}
change2();
print $n . "\n"; //100

function change3()
{
    global $n;
    $n = 15;
}
change3();
print $n . "\n";//15


グローバル関数の指定には2種類ある

$GLOBALS['a'];
global $n;

①について

$GLOBALS['a']; は関数内からグローバルスコープへのアクセスが可能になる。
'a'の部分に変数の$を除いた値を入れると使用可能(今回は$aの為'a')
$GLOBALS['a'] = 'hoge';
のように値を変更できる

②について

global $n
$n = 'hoge';
とすることで変更可能に

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?