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

1

8

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

Burnett answered 6/8, 2015 at 5:6 Comment(0)
J
12

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.

Joplin answered 6/8, 2015 at 5:49 Comment(1)
If you're using PHP 5.6+ you can go one step further and define the namespace for your helper function. That will avoid any naming conflicts - and you can import that function where you use it so you can still call it simply as fn(). Much better IMHO than adding it to the global namespace.Hidalgo

© 2022 - 2024 — McMap. All rights reserved.