Skip to content
Advertisement

Adding a namespace to the top of my PHP functions page results in the display of an entirely blank page (with no errors)

I am using PHP Version 7.3.25.

I have started experimenting with PHP Namespaces on the server-side (not least because I use ESModules on the client-side and I fully appreciate the advantages of namespacing) but I have fallen at the first hurdle – it’s probably an obvious rookie error, but with no errors displaying it’s difficult to guess what mistake I’ve made.

I have a long page of global functions – included before anything else by every page on the website – which I have prepended with:

namespace mySetupmyFunctions;

On every page on the site, I include this long page of global functions, using:

include $_SERVER['DOCUMENT_ROOT'].'/my-setup/my-functions.php';

getMyPage();

I can’t guess what is going wrong now because the result (for every page) is now an entirely blank page with no error.

Although the long page only contains functions (no classes), I wondered if I might need to change the function invocation getMyPage(); to:

mySetupmyFunctionsgetMyPage();

But that also doesn’t work. So I’m a little lost, unable to even guess at what basic, low-level consideration is going wrong or which I’ve missed.

Advertisement

Answer

Yes, you either have to prefix the function with its namespace (use the fully qualified name of it) or alias the function before calling it using the use statement (usually right after the namespace declaration – if any – or at the beginning of the file otherwise).

<?php

use mySetupmyFunctionsgetMyPage;

...

include $_SERVER['DOCUMENT_ROOT'].'/my-setup/my-functions.php';

getMyPage();

Note that the use ... statement does not import the function per se. It only creates a short alias for it, so you won’t have to use the FQN. The official documentation is pretty useful for learning the basics, but only you have to keep in mind this slight misuse of “importing” keyword.

EDIT: Namespaces can be used for autoloading (auto-importing) of classes (functions not supported), take a look at spl_autoload_register for the basics, then consider using Composer.

EDIT 2: Also the blank page means a fatal error with error reporting / displaying turned off. Check the PHP log, the error will be there.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement