Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use function doesn't import functions in PHP

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.


enter image description here

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.

like image 209
arnolds Avatar asked Jul 26 '18 21:07

arnolds


1 Answers

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.

like image 80
MC57 Avatar answered Oct 23 '22 18:10

MC57