Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

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.

question from:https://stackoverflow.com/questions/65859047/adding-a-namespace-to-the-top-of-my-php-functions-page-results-in-the-display-of

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...