Get "PHP 8 in a Nuthshell" (Soon includes PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Import and export only a function under namespace in PHP

The standard way of including files in modern PHP development is using namespaces and autoloading of classes using Composer.

So, for instance, if I have the autoload setup like following in my composer.json

{
    ...
    "autoload": {
        "psr-4": {
            "App\\": "app/"
        }
    }
    ...
}

…And I have a file called HelloWorld.php under app/ which contains a HelloWorld class, we can define it using namespace like so.

<?php

namespace App;

class HelloWorld
{

}

You can use/import this class in other files like so.

use App\HelloWorld;

A function under a namespace

Recently, I was going through all the new features of Laravel 8 and I saw this queueable function which can be used to mark the closure based listeners as “queueable”. And this is the first time where I’ve seen only a function being defined under a namespace.

If we look closely at the source code of it, we get to know that the queueable function lies under the Illuminate\Events namespace like so.

//src/Illuminate/Events/functions.php

<?php

namespace Illuminate\Events;

use Closure;

if (! function_exists('Illuminate\Events\queueable')) {
    /**
     * Create a new queued Closure event listener.
     *
     * @param  \Closure  $closure
     * @return \Illuminate\Events\QueuedClosure
     */
    function queueable(Closure $closure)
    {
        return new QueuedClosure($closure);
    }
}

As you can tell, the src/Illuminate/Events/functions.php only contains a function queueable under the namespace Illuminate\Events.

And because it’s under a namespace, you can import it elsewhere using the use function operator like so and start using it just like that.

use function Illuminate\Events\queueable;

Usefulness

This is especially useful, in my opinion, in scenarios where you don’t want to create an entire class for a single function but still want to keep it under a namespace so that it’s easily importable like in the case of this queueable function.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?