// Trying to access the MyProjectFileAccessInput class // This time it will work because we use the fully qualified name, note the leading backslash $input = new MyProjectFileAccessInput();
// We want to access the global Exception class // The following will not work because there"s no class called Exception in the MyProjectDatabase namespace and unqualified class names do not have a fallback to global space // throw new Exception("Query failed!");
// Instead, we use a single backslash to indicate we want to resolve from global space throw new Exception("ailed!");
function var_dump() { echo "Overloaded global var_dump()!<br />"; }
// Include a variable file require strtolower($project_name . "/". $package_name . "/" . $class_name) . ".php";
// Name of a variable class in a variable namespace. Note how the backslash is escaped to use it properly $fully_qualified_name = $project_name . "\" . $package_name . "\" . $class_name;
这个关键字对于判断当前代码是否从命名空间开始时非常有用,而且也可以用来调试代码。 导入或别名 PHP中得命名空间也支持导入,导入也被成为别名。只有类、接口和命名空间可以被导入(别名)。导入是命名空间中一个非常有用和基础的功能。它使我们可以使用外部的代码包,而不用担心名字的冲突。使用use关键字可以实现导入功能。也可以使用as关键字,在导入的时候指定一个别名。 复制代码 代码如下: use [name of class, interface or namespace] as [optional_custom_alias]
// This holds the MyProjectDatabase namespace with a Connection class in it require "myproject/database/connection.php";
// If we want to access the database connection of MyProject, we need to use its fully qualified name as we"re in a different name space $connection = new MyProjectDatabaseConnection();
// Import the Connection class (it works exactly the same with interfaces) use MyProjectDatabaseConnection;
// Now this works too! Before the Connection class was aliased PHP would not have found an OtherProjectConnection class $connection = new Connection();
// Import the MyProjectDatabase namespace use MyProjectDatabase;