Should I namespace global functions in PHP?

前端 未结 3 474
死守一世寂寞
死守一世寂寞 2021-01-02 00:49

In PHP, I\'m using namespaces at the class level. However, Netbeans keeps telling me namespace my global functions as well. For example, if I type

str_replac         


        
相关标签:
3条回答
  • 2021-01-02 01:00

    Overzealous for sure, but I can't reproduce this is Netbeans 7.0.1, with PHP Plugin 1.17.1. It's not the convention, anyway, and I would not consider it a best practice at all.

    0 讨论(0)
  • 2021-01-02 01:11

    Netbeans is simply not following the documented rules of resolving namespaces as documented:

    1. global classes (like DateTime) need to be qualified otherwise, PHP will look for that class in the current namespace.
    2. global functions (like array_filter) and constants will be found in the global namespace (without explicit qualification) if they do not exist in the current namespace.

    In other words, your code should be considered idiomatic based on the documented rules.

    0 讨论(0)
  • 2021-01-02 01:14

    There is no such recommendation in

    • http://php.net/manual/en/language.namespaces.php

    Nor is it necessary to use the global identifer since PHP will fallback to the global function definition when there is no function of that name in the current namespace.

    With that said, the only reason to add the identifier is to make it more explicit that you want to use the actual global thing to prevent accidental changes in code behaviors when someone adds a function of the same name into the current namespace.

    You might want to ask on the Netbeans Mailing List for more details about why your IDE suggests this.

    0 讨论(0)
提交回复
热议问题