简体   繁体   中英

PHP Global Namespace Function

In PHP, I can access a function in global namespace from another namespace using myFunc() , instead of \\myFunc() . PHP Will automatically fallback to the global namespace, if myFunc cannot be resolved in the current namespace.

Which is the recommended way? \\myFunc() or myFunc() ?

Second option is better if you want to implement some kind of polymorphism or to completely change function's logic. Something like this.

namespace Nkamm;

// like a PHP6
function strstr($needle, $haystack)
{
    return \strstr($haystack, $needle);
}

var_dump(strstr('t', 'Long test'));

Result:

string(4) "test"

But I would not like to do such "overloads" because that will cause the mess (until they are strictly documented in project). Hence there is no sense to overwrite existing functions.

Summing up: keep your functions in your namespace, use global functions without any backslashes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM