Reputation: 411
Trying to understand how namespace in php works and am stuck.
This below is the architecture of the project.
Class: Loader.php (suppose to load controller/model/ library but for now gibberish test codes)
namespace system\core;
class Loader
{
public function index()
{
echo 'loader';
}
public function controller($pathtocontroller)
{
// Echo path to the controller
echo $pathtocontroller;
}
}
index.php
require 'system/core/Loader.php';
require 'system/core/BaseController.php';
require 'app/controller/common/HomeController.php';
use system\core;
use app\controller;
$loader = new \system\core\Loader();
$loader->controller(app\controller\common\HomeController);
and this is the error I get
Fatal error: Undefined constant 'app\controller\common\HomeController' in C:\xampp\htdocs\psrstd\index.php on line 20. Lin 20 on index is $loader->controller(app\controller\common\HomeController);
Expected Result: app/controller/common/HomeController
in case you wondering what's in there at the HomeController (again gibberish test code)
namespace app\controller\common;
use system\core\BaseController;
class HomeController extends BaseController
{
public function index()
{
echo 'home';
}
}
Upvotes: 3
Views: 5050
Reputation: 8298
you are passing a constant type to your controller method,
you are aiming to pass an object [ dependency injection
] so you will need to instantiate your argument like :
$loader->controller(new \app\controller\common\HomeController);
otherwise you may send this argument as a string like :
$loader->controller("\\app\\controller\\common\\HomeController");
and instantiate that object within your method [ as a factory method
]
public function controller($pathtocontroller)
{
// new $pathtocontroller and so on
}
Further reading :
Upvotes: 1