"Call to undefined function" when calling a function in custom composer package

Viewed 1796

PHP experts! I'm trying to make my code more modular according to the ways of PHP (using 7.0) and this is my first experiment creating my own combination of namespace + composer package + git repository.

My package directory:

packagedir
|__src
|   |__myfunc.php
|__composer.json

myfunc.php:

namespace MyNS\MySubNS;
function myfunc() { return 1; }

packagedir/composer.json:

{
  "name": "myns/mysubns",
  ...
  "autoload": {
    "psr-4": { "MyNS\\MySubNS\\": "src" }
  }
}

All checked into repository packagedir/.git.

My project directory after composer install:

public_html
|__vendor
|   |__composer
|   |   |__ [all the usual autoload_* stuff, etc.]
|   |__myns
|   |   |__mysubns 
|   |       |__src
|   |       |   |__myfunc.php
|   |       |__composer.json
|   |__autoload.php
|__composer.json
|__composer.lock
|__index.php

public_html/composer.json:

{
  "require": {
    "myns/mysubns": "dev-master"
  },
  "repositories": [
    { "type": "git",
      "url": "file:///path/to/packagedir/.git" }
  ]
}

index.php:

ini_set('display_errors','1');
require_once 'vendor/autoload.php';
echo \MyNS\MySubNS\myfunc();

It looks like composer installed the package in vendor, and autoload_ps4.php includes:

return array(
    'MyNS\\MySubNS\\' => array($vendorDir . '/myns/mysubns/src'),
);

But I get:

( ! ) Fatal error: Uncaught Error: Call to undefined function MyNS\MySubNS\myfunc() in /var/www/public_html/index.php on line 3
( ! ) Error: Call to undefined function MyNS\MySubNS\myfunc() in /var/www/public_html/index.php on line 3

Can anyone see what I'm doing wrong (aside from the advice that .git repositories are not recommended as a place to get packages)?

1 Answers

PHP does not autoload functions. Use the files autoloader, eg:

{
    "autoload": {
        "files": ["src/MyLibrary/functions.php"]
    }
}

or enclose them in a class and autoload that, eg:

namespace foo;
class Helper {
    public static function foo() { ... }
}
Related