什么是名称空间?如何在PHP中实现名称空间? [英] What is a namespace and how is it implemented in PHP?

查看:75
本文介绍了什么是名称空间?如何在PHP中实现名称空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听说最新的PHP支持名称空间.我知道在全局范围内定义的变量具有 no 命名空间,那么如何在另一个命名空间中创建变量?

I've heard the latest PHP has support for namespaces. I know variables defined in the global scope have no namespace, so how does one make a variable in a different namespace?

这仅仅是对变量/函数进行分类的一种方法吗?

Is it just a way of categorising variables/functions?

推荐答案

命名空间是一种用于组织变量,函数和类的编程语言机制. PHP 5.3添加了对名称空间的支持,我将在以下示例中进行演示:

Namespaces are a programming language mechanism for organizing variables, functions and classes. PHP 5.3 adds support for namespaces, which I'll demonstrate in the following example:

假设您想合并两个使用相同类名 User 的项目,但是每个项目都有不同的实现:

Say you would like to combine two projects which use the same class name User, but have different implementations of each:

// Code for Project One (proj1.php)
<?php
  class User {
    protected $userId;
    public function getUserId() {
      return $this->userId;
    }
  }
  $user = new User;
  echo $user->getUserId();
?>

// Code for Project Two (proj2.php)
<?php
  class User {
    public $user_id;
  }
  $user = new User;
  echo $user->user_id;
?>

<?php
  // Combine the two projects
  require 'proj1.php';
  require 'proj2.php'; // Naming collision!
  $myUser = new User; // Which class to use?
?>

对于低于5.3的PHP版本,您将不得不为一个项目使用的 User 类的所有实例更改类名,以防止命名冲突:

For versions of PHP less than 5.3, you would have to go through the trouble of changing the class name for all instances of the class User used by one of the projects to prevent a naming collision:

<?php
  class ProjectOne_User {
    // ...
  }
  $user = new ProjectOne_User; // Code in Project One has to be changed too
?>

对于大于或等于5.3的PHP版本,可以在创建项目时通过添加名称空间声明来使用名称空间:

For versions of PHP greater than or equal to 5.3, you can use namespaces when creating a project, by adding a namespace declaration:

<?php
  // Code for Project One (proj1.php)
  namespace ProjectOne;
  class User {
    // ...
  }
  $user = new User;
?>

<?php
  // Combine the two projects
  require 'proj1.php';

  use ProjectOne as One; // Declare namespace to use

  require 'proj2.php' // No collision!

  $user = new \One\User; // State which version of User class to use (using fully qualified namespace)

  echo $user->user_id; // Use ProjectOne implementation
?>

有关更多信息:

  • PHP.net Namespaces
  • PHP Namespaces

这篇关于什么是名称空间?如何在PHP中实现名称空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆