0

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

user2145184
  • 440
  • 4
  • 15

2 Answers2

2

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.

Devon Bessemer
  • 34,461
  • 9
  • 69
  • 95
  • 1
    I was confused by those other answers. As I have multiple 3rd party libraries which call standard php functions in their namespaced classes. They dont have a backslash in front of every hundredth built in php function ... but the class define files are riddled with name spaces (like for example, the paypal rest api). So your answer makes the most sense! – IncredibleHat Nov 11 '17 at 15:13
  • It's necessary if there is another namespace which defines a function with the same name. – Tom Mettam Nov 11 '17 at 15:15
  • 1
    @TomMettam If you had defined another function in the current namespace named getallheaders(), then you would use `\getallheaders()` to access the global one, but that isn't the case here. – Devon Bessemer Nov 11 '17 at 15:20
  • This is the correct answer. The problem was that when I converted my code into a namespaced class I also dropped some libraries. One of said libraries probably defined getallheaders for nginx. – user2145184 Nov 11 '17 at 15:23
0

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.

Jesse Schokker
  • 896
  • 7
  • 19