以前我可以这样做:
/var/www/laravel/app/Http/Controllers/HelloController.php
<?php namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Models\Hello\Hello as Hello;
class HelloController extends Controller {
public function index() {
$o = new Hello;
$o = new Hello('changed1','changed1');
var_dump($o);
}
}
的/ var / WWW / laravel /应用/型号/你好
<?php namespace App\Models\Hello;
use Illuminate\Database\Eloquent\Model\Hello.php;
class Hello extends Model
{
public function __construct($one='default1', $two='default2')
{
echo "First Param: $one","\n<br>\n";
echo "Second Param: $two","\n<br>\n";
echo "\n<br>\n";
}
}
routes.php文件
Route::get('tutorial', function() {
$app = app();
$app->make('Hello');
});
在没有make的情况下实例化,但现在会出现错误:
ReflectionException in Container.php line 776: Class Hello does not exist
你认为我在这里失踪了什么?
答案 0 :(得分:4)
由于您的类的namespace
为App\Models\Hello
,因此在尝试实例化类时必须使用namespace
。因此,您的代码应该是这样的:
Route::get('tutorial', function() {
$app = app();
$app->make('App\Models\Hello\Hello');
});
要在答案中展开一点,您可以删除make()
方法调用,只需使用app()
帮助程序,您最终会得到相同的结果:
Route::get('tutorial', function() {
$app = app();
$app->make('App\Models\Hello\Hello');
// you can achieve the same with the
// `app()` helper using less characters :)
app('App\Models\Hello\Hello');
});