douweng7083 2014-08-31 18:49
浏览 130
已采纳

Composer psr-0自动加载自定义命名空间不起作用

I have trouble adding my own namespaces to composer with PSR-0. I have read this and this but I still can't make it work

composer.json

{
"require": {
    "klein/klein": "2.0.x",
    "doctrine/orm": "2.4.4"

},
"autoload": {
    "psr-0": {
        "mynamespace":        "src/"
        }
}
}

The src folder is placed inside the same directory as composer.json

The src directory has the following structure

src
└── mynamespace
    ├── Keys.php

Keys.php

<?php
namespace mynamespace\Keys;

define ("API_KEY", "XXXXXXXXXXXX");
?>

index.php

use Klein\Klein;
use mynamespace\Keys;
require_once __DIR__ . '/vendor/autoload.php';

$klein = new Klein(); // works
echo API_KEY;  // Undefined constant
  • 写回答

1条回答 默认 最新

  • duanhan5230 2014-08-31 20:09
    关注

    You can only load classes, interfaces and traits with autoloading.

    Because all you do is add a use clause which does not do anything by itself with autoloading (i.e. it does not load something), and you do not use a class, nothing happens.

    I recommend using class constants. They may be put into classes or interfaces:

    namespace mynamespace;
    
    interface Keys {
        const API_KEY = 'XXXXXXXX';
    }
    
    use mynamespace/Keys;
    echo Keys::API_KEY;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何利用支持向量机提高分类器正确率和筛选理想分类器
  • ¥15 Pygame坦克大战游戏开发实验报告
  • ¥15 用vmmare虚拟机用sentaurus仿真的时候,调用terminal程序,输入swb指令弹出这个,打不开workbench,桌面上面的sentaurus workbench也打不开
  • ¥15 simulink 硬件在环路仿真
  • ¥15 python动态规划:N根火柴摆出的最大数字
  • ¥20 (标签-excel)
  • ¥200 求idea10和MyEclipse7.1
  • ¥20 vb6.0截取当前窗体保存为jpg文件
  • ¥20 苹果手机不使用大疆sdk怎么获取遥控器控制信息或如何接入大疆sdk并且成功上架sdk
  • ¥20 woocommerce 注册按键重定向