Wonderful! WordPress

いまさらの php の global と $GLOBALS と

phpの場合、関数のブロックの内側というローカルで、グローバルな変数を操作する場合は、キーワードのglobalを使って変数を宣言しておくか、連想配列の$GLOBALSを使います。

<?php
    $test = 1;

    function test_global() {
        global $test;
        
        $test++;
         
        echo $test;// -> 2
    }

    test_global();
?>

$GLOBALSを使うなら、

<?php
    $test = 1;

    function test_global() {
        
        $GLOBALS['test']++;

    }

    test_global();
    echo $test; // -> 2
?>

とか言う具合。

んで、globalであればこんなこともできる。

<?php

    function test_global() {
        global $test;
        
        $test++;
    }

    test_global();
    echo $test;// -> 1
?>

上との違いは、もともとの対象となるグローバルな変数が存在してるかってことだけ。
ここからが本題なんだけれど、もともとの対象となるグローバルな変数が存在していなくても、関数のブロック内からグローバルな変数を宣言できる。
じつは、自分勝手な思い込みなのだけれど、存在しない変数をglobalで指定するとエラーになるものとばかり思ってたのです。なんでだろう?
phpの場合、変数は代入すれば使えてしまうので、宣言してというイメージがなかったからなのかもしれないけれど。まぁ、なんにしてもこれでエラーが出ることもなく、関数内で宣言した変数がグローバルとして作動する。
もちろん、これでglobalでの宣言がなければ、関数の内でも外でもエラーとなってしまう、そりゃ、当然でした。
ちなみに、globalで変数を宣言した時の価は null 。

これは極めて基本的で常識的なことなのかもしれないけれど、またしてもいまさらでふと気になったことで・・・。
と、いうのは WordPress において複数のテンプレートで、たとえば header.phpfooter.php とかで変数を共有したい場合など、双方のテンプレートにおいてその変数を global にしておけば良いのだけれど、その変数がもともと存在しなかったらどうなるのかしら?と、ふと思ったのがきっかけ。まぁ、実際にそうなっていた部分もあって、でもエラーにはなっていないしで、いまさらながら認識を確実なものにしようと、ちょっと再確認してみたというわけですな。
なんにしても、グローバル変数の使用は必要最小限に!ということに変わりはないですけれど。

Leave a Reply!

JavaScript is necessary to send a comment.
You can edit and delete your comment if you input a edit key.
Edit key is necessary for attesting you when you edit and delete it.
The tag of HTML cannot be used in comment.
When you comment for the first time, it is displayed after the approval of the administrator.
Because I cannot speak English so much, it takes time to answer.
Required fields are marked *.

※Please enter more than 5 characters only alphabets.
※Edit or delete are possible for 2000 days after approval.

*

♠Simplistic Comment User Editable v4.0

♠When visitors leave comments on the site this site collect the data shown in the comments form, and also the visitor’s IP address and browser user agent string to help spam detection.
♠This site does not use cookie when visitors leave comments and commenter edit comment.
♠This site uses Akismet to reduce spam. Learn how your comment data is processed.

Comments feed

Trackback URL : https://strix.main.jp/wp-trackback.php?p=163122

Sanbanse Funabashi
2011.01.01 sunrise

Top

スクロールさせるか画像をクリックすると元に戻ります。