Composer autoload full example?

本秂侑毒 提交于 2019-12-03 00:39:19
edigu

According to PSR-4, The fully qualified class name MUST have a top-level namespace name, also known as a "vendor namespace" and underscores have no special meaning in any portion of the fully qualified class name.

Try this:

cd ~
mkdir -p testproj/src/MyApp/Package
cd testproj
composer init && composer update

Create your index.php with this content:

<?php
$loader = require 'vendor/autoload.php';
$loader->add('MyApp\\', __DIR__.'/src/');
$a = new MyApp\Package\Obj();
var_dump($a);

And put the Obj class (src/MyApp/Package/Obj.php) :

<?php
namespace MyApp\Package;

class Obj
{}

Now when you run the code:

php index.php

You should get this as output:

class MyApp\Package\Obj#2 (0) {
}

Also directory scaffolding should look like this:

testproj
├── composer.json
├── index.php
├── src
│   └── MyApp
│       └── Package
│           └── Obj.php
└── vendor
    ├── autoload.php
    └── composer
        ├── ClassLoader.php
        ├── autoload_classmap.php
        ├── autoload_namespaces.php
        ├── autoload_psr4.php
        └── autoload_real.php
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!