简体   繁体   中英

How can I prevent built in PHP functions from becoming namespaced?

I'm new to PHP namespaces, what I have is:

namespace Foo\Bar;
class JsonAssetRest{
    static function ini(){
        $headers = getallheaders(); 
    }
}
JsonAssetRest::ini();

And this is creating the error

Uncaught Error: Call to undefined function Foo\Bar\getallheaders() in /var/www/html/class JsonAssetRest.php

How do I use getallheaders() (the built in function) without getting this error?

Edit: The issue was related to removing a library while I was converting my code to a namespaced class . Said library defined getallheaders for nginx. I was confused by the error message adding namespacing and thought that was the issue.

Gonna leave this up in case someone else gets confused by the error while debugging. And because the comments have improved my understanding of namespacing in PHP.

Edit2: In case someone stumbles upon this error and wants to know how to solve the actual problem (getallheaders not being defined under nginx), it's been answered here: Get the http headers from current request in PHP

Global functions are available from any namespace. You do NOT need to add a \\ prefix like the other answers suggest.

This error means that there is no function defined in the global or current namespace named getallheaders(). This function is an alias to apache_response_headers() which also likely doesn't exist. I'm assuming that PHP is not running as an apache module which is required for these functions.

By adding a backslash in front of the function like so: $headers = \\getallheaders();

If you do not add this backslash in front of the function, it will assume that the function is in the same namespace as the class it is called from. Adding the backslash makes it so that it will look for that function in the global namespace, which is where the function lives.

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