We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Can't get use function to work

I'm using a micro framework, generated by the command line tools, and want to (as a proof of concept) use functional programming.

I have a file (app/Library/Responses/JsonResponse.php - namespace OfficeApi\Library\Responses) with a function (json _ response) inside it. In app.php i've added the appropriate use statement:

use function OfficeApi\Library\Responses\json_response;

but when I try to call json _ response if get the following:

Fatal error: Uncaught Error: Call to undefined function OfficeApi\Library\Responses\json_response() in /Users/.../office-api-micro/app/app.php on line 18

Can anyone help me?

If I use a class with static methods, it works fine.


My guess is that Phalcon\Loader does not handle function import autoloading.

Try registering the file explicitly:


I tried that, and I get the same error.

I played around with the code you gave me, and got it to work:

$loader->registerFiles( [ APP_PATH . '/library/Responses/JsonResponse.php' ] );

The only real complaint I have about this is that I would prefer to just register the library root, and have it automaticallt recurse.

I tried registerDirs and using a wildcard in registerFiles, but they don't work.

edited Jan '18

Function autoloading is not a widely used feature, even composer doesn't support it (only by explicitly registering files, same as Phalcon)

Having plain functions is somewhat of an anti-pattern in PHP. You're better off using static methods, as you've mentioned before.

edited Jan '18

I saw that. What I did was write a recursive directory lister for the Library folder. Not exactly perfect, but good enough for now.

Also, I know plain functions are a bit of an anti-pattern, and am completely happy with static methods, but I needed this for my proof of concept.

Thanks for your help!

Update: I spoke with my colleagues, and we decided to go with static methods after all. Better than hacking pure functions into Phalcon