Search code examples
phpfunctionnamespacescomposer-phpglobal-namespace

Make a function that is declared in an autoloaded, namespaced class file, into a global function


My requirement might seem like awful practice, but none the less I would like to know if it's doable.

I'm using composer to autoload my classes. In one of the class files, I want to define a function that can be used as a shorthand within the global namespace. Because of composer's requirements, the class needs to be namespaced.

My question: Is there any way via minor alterations that I could get this working?

MyClass.php:

<?php

namespace Jodes;

class MyClass {
    public function __construct() {
        echo "I am the class";
    }
}

function fn(){
    echo "I am a shorthand for doing stuff";
}

index.php:

<?php

require_once '../vendor/autoload.php';

use Jodes\MyClass;

new MyClass();

// Jodes\fn();  // works
// fn();        // doesn't work

composer.json

{
    "name": "jodes/mypackage",
    "autoload": {
        "psr-4" : {
            "Jodes\\" : "src"
        }
    }
}

I've tried everything I can think of without luck, despite reading more links than I can count.

Thanks


Solution

  • First of all, if this function is not a part of MyClass, it shouldn't be put in the same file. The convention is to put each class (and only that class) in separate files.

    For helper function like your fn() that should be available globally, you're gonna need a separate file. Declare the function there in the global namespace, and then add to your composer project using composer's files mechanism:

    //common.php
    <?php
    function fn() {
      // some code
    }
    
    //composer.json
    "autoload": {
        "files": ["path/to/common.php"]
    }
    

    This will load your common.php file for every request and make your helper functions available.