CakeFest 2024: The Official CakePHP Conference

全局空间

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

如果没有定义任何命名空间,所有的类与函数的定义都是在全局空间,与 PHP 引入命名空间概念前一样。在名称前加上前缀 \ 表示该名称是全局空间中的名称,即使该名称位于其它的命名空间中时也是如此。

示例 #1 使用全局空间说明

<?php
namespace A\B\C;

/* 这个函数是 A\B\C\fopen */
function fopen() {
/* ... */
$f = \fopen(...); // 调用全局的fopen函数
return $f;
}
?>

add a note

User Contributed Notes 6 notes

up
58
routinet
12 years ago
Included files will default to the global namespace.
<?php
//test.php
namespace test {
  include
'test1.inc';
  echo
'-',__NAMESPACE__,'-<br />';
}
?>

<?php
//test1.inc
 
echo '-',__NAMESPACE__,'-<br />';
?>

Results of test.php:

--
-test-
up
3
PhoneixSegovia at gmail dot com
1 year 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;
up
14
nobody at example dot com
8 years ago
In namespaced context the Exception class needs to be prefixed with global prefix operator.

<?php

namespace hey\ho\lets\go;

class
MyClass
{
    public function
failToCatch()
    {
        try {
           
$thing = somethingThrowingAnException();
        } catch (
Exception $ex) {
             
// Not catched
       
}
    }

    public function
succeedToCatch()
    {
        try {
           
$thing = somethingThrowingAnException();
        } catch (
\Exception $ex) {
             
// This is now catched
       
}
    }

}
up
1
dmc60 at cam dot ac dot uk
2 months 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.
up
-29
hileon at gmail dot com
8 years ago
This design of access globe name is bad, at least inconvenient.
In case that you have some legacy code, and try to copy and re-use it under some namespace. You have to add prefix "\" on any global function call.
up
-43
xmarcos at gmail dot com
11 years ago
That's the expected behavior, you have to declare the namespace at the top of the file to "extend" it.

If you include a global namespaced file, it will operate on the global namespace.
To Top