What is a namespace and how is it implemented in PHP?

后端 未结 4 1886
清歌不尽
清歌不尽 2021-02-03 14:28

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 na

4条回答
  •  孤城傲影
    2021-02-03 15:09

    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:

    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)
    userId;
        }
      }
      $user = new User;
      echo $user->getUserId();
    ?>
    
    // Code for Project Two (proj2.php)
    user_id;
    ?>
    
    
    

    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:

    
    

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

    
    
    user_id; // Use ProjectOne implementation
    ?>
    

    For more information:

    • PHP.net Namespaces
    • PHP Namespaces

提交回复
热议问题