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

后端 未结 4 1888
清歌不尽
清歌不尽 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 14:49

    Namespaces solve the problem of naming collisions when importing classes and functions from libraries.

    Without namespaces, if you include two libraries which happen to define a function/class with the same name (ie, two libraries that both include a class called 'user'), it will fail.

    With no namespace support in PHP, most libraries have taken to prefixing their function/class names with something that is likely to be unique, in an attempt to avoid name collisions. The trouble is, this creates longer function or class names.

    The example given here is of the exception class:

    PEAR_Form_Loader_Validate_Table_Element_Validator_Exception.
    

    You can import from a long namespace into your own local scope as an alias using the 'AS' keyword - a name you choose. Thus, you can still have a short class name of your choice in your local scope.

    The following applies an 'alias' called DbConnection to Zend::DB::Connection.

    use Zend::DB::Connection as DbConnection
    

提交回复
热议问题