Movatterモバイル変換


[0]ホーム

URL:


update page now
    グローバル関数/定数への移行 »
    « エイリアス/インポート

    グローバル空間

    (PHP 5 >= 5.3.0, PHP 7, PHP 8)

    名前空間の定義がない場合、すべてのクラスや関数の定義はグローバル空間に配置されます。 これは、名前空間に対応する前の PHP がサポートしていた空間です。 名前の先頭に\ をつけると、 名前空間の内部からであってもグローバル空間の名前を指定することができます。

    例1 グローバル空間を指定する方法

    <?php
    namespaceA\B\C;

    /* この関数は A\B\C\fopen です */
    functionfopen() {
    /* ... */
    $f=\fopen(...);// グローバルな fopen をコールします
    return$f;
    }
    ?>

    Found A Problem?

    Learn How To Improve This PageSubmit a Pull RequestReport a Bug
    add a note

    User Contributed Notes4 notes

    routinet
    14 years ago
    Included files will default to the global namespace.<?php//test.phpnamespacetest{  include'test1.inc';  echo'-',__NAMESPACE__,'-<br />';}?><?php//test1.incecho'-',__NAMESPACE__,'-<br />';?>Results of test.php:---test-
    nobody at example dot com
    10 years ago
    In namespaced context the Exception class needs to be prefixed with global prefix operator.<?phpnamespacehey\ho\lets\go;classMyClass{    public functionfailToCatch()    {        try {$thing=somethingThrowingAnException();        } catch (Exception $ex) {// Not catched}    }    public functionsucceedToCatch()    {        try {$thing=somethingThrowingAnException();        } catch (\Exception $ex) {// This is now catched}    }}
    dmc60 at cam dot ac dot uk
    1 year ago
    To define an associative array (hash) so that it is part of the namespace, instead of going into the global namespace, just declare it as const, istead of as a variable.This is handy for lookup tables, config settings, etc.// Example.  Instead of writing:$my_datatypes = [    "sterility" =>  [      "xlsx" => [        "Sample Type",        "Run Pass/Fail",        "Result"       ],      "db" => [        "SampleType",        "RunPassFail",        "Result"       ]    ]];// ...declare the lookup table like this:const MY_DATATYPES = [    "sterility" =>  [      "xlsx" => [        "Sample Type",        "Run Pass/Fail",        "Result"       ],      "db" => [        "SampleType",        "RunPassFail",        "Result"       ]    ]];// ...and it will be declared within the current namespace.
    PhoneixSegovia at gmail dot com
    3 years ago
    Note that variables aren't part of the namespace so they are always global (or scoped to function, etc.) and can't be accessed the same way as other namespace stuff.So no:    namespace Foo;    $var = "hello";    echo \Foo\$var;
    add a note
    To Top
    and to navigate •Enter to select •Esc to close •/ to open
    PressEnter without selection to search using Google

    [8]ページ先頭

    ©2009-2025 Movatter.jp