Can't import functions using the use function
keywords described in PHP.net. Recreating the example locally is returning a PHP Fatal error: Uncaught Error: Call to undefined function
.
composer.json
{
"autoload": {
"psr-4": {
"My\\": ""
}
}
}
full.php
<?php
namespace My\Full;
function functionName()
{
echo 'Hello Stackoverflow';
}
index.php
<?php
require 'vendor/autoload.php';
use function My\Full\functionName as func;
func();
Note: I understand I can require the file, but I wanted to know if it was possible without doing so.
use function
does not include any files or function definitions it simply aliases a fully qualified function name meaning when you call the function you don't need to specify the namespace.
In your example you are using composer which is great for automatically including files however from https://www.php-fig.org/psr/psr-4/ PSR-4 is
a specification for autoloading classes from file paths
It does not autoload functions or files which don't conform to this specification.
You can however use composer to automatically include files for situations like this. You need to update your composer.json then run composer dumpautoload
composer.json
{
"autoload": {
"files": ["full.php"]
}
}
The rest of your can then remain unchanged and it should work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With