2014-12-09 109 views
2

我正在阅读一些关于为Laravel创建自定义类的教程。我也跟着指示,做什么教程说:Laravel - 自定义类不工作

  1. 创建新的文件夹laravel /应用/库/图形/

  2. 编辑laravel /程序/启动/ global.php,我说:

    app_path().'/libraries/graphics', 
    
  3. 创建于laravel /应用/库/图形/命名Image.php与此代码的新文件:

    <?php namespace graphics/Image; 
    
    class Image { 
    
        public static function hello() { 
    
        return 'Hello'; 
    
        } 
    } 
    
  4. 二手composer dump-autload命令

  5. Route::get('/' , function() { return Graphics\Image::hello(); });将返回错误:

Use of undefined constant graphics - assumed 'graphics'

我还添加"app/libraries/graphics/Image.php"线进入composer.json autload部分,它不应该是neccessary。为什么我得到这个错误?每个教程都显示相同的过程,但为什么它不起作用?

+2

你们用一个反斜杠命名空间“\”而不是“/” – lukasgeiter 2014-12-09 12:09:41

+0

然后我得到错误“类图形\图像不存在” – 2014-12-09 12:12:12

+2

因为你的命名空间,包括类是'图形\图像\ Image' 。如果你想'Graphics \ Image',你需要将你的名字空间改为'Graphics'。 – Marwelln 2014-12-09 12:14:24

回答

1

应该不是你的名字空间只是graphics?当前文件创建graphics\Image\Image。尝试从您的名称空间中删除Image

<?php namespace graphics; 

class Image { 

    public static function hello() { 

    return 'Hello'; 

    } 
} 
+1

如果我使用“namespace graphics \ Image;”然后“return graphics \ Image \ Image :: hello();”有用。但是如果我使用“命名空间图形”和“return graphics \ Image :: hello();”那么它不起作用返回相同的错误。为什么? – 2014-12-09 12:26:34

0

你不需要为自己混淆。我解决问题纳入Laravel 5.你并不需要添加“应用程序/库/图形/ Image.php”行成composer.json autload节,因为By default, app directory is namespaced under App and is autoloaded by Composer using the PSR-4 autoloading standard.

<?php 
namespace App\libraries\graphics; 
class Image { 
    public static function hello() { 
     return 'Hello'; 
    } 
} 

,现在用你的形象从类你的路线。

Route::get('graphics',function(){ 
    echo \App\libraries\graphics\Image::hello(); 
});