L
L
Luigi2021-04-08 23:38:40
PHP
Luigi, 2021-04-08 23:38:40

Why is the class object not being created?

I am creating an MVC application framework using composer and the AltoRouter library. I didn’t forget about .htaccess, I direct all requests to Index.php, however, when I want to process the route, I don’t have an instance of the IndexController class.
Error: Uncaught Error: Class 'IndexController' not found in C:\xampp\htdocs\routetest\public\index.php:18 Stack trace: #0 {main} thrown in C:\xampp\htdocs\routetest\public\index .php on line 18
I do it like this: However, if you write it like this: $obj = new IndexController(); The error disappears. I don't know why. Here is the whole index.php file

$obj = new $controller();



<?php

use routetest\Controllers\IndexController;

require_once dirname(__DIR__) . '/vendor/autoload.php';


$router = new AltoRouter();
$router->setBasePath('/routetest');


$router->map('GET', '/', 'IndexController#index', 'index');

$match = $router->match();


list($controller, $action) = explode('#', $match['target']);

list($controller, $action) = explode('#', $match['target']);
$obj = new $controller();


Project Structure
606f69ca52993715519440.jpeg

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Hog, 2021-04-09
Wampa @Annikangl

use does not work in this case.
because you dynamically create an object, you need to explicitly specify the namespace routetest\Controllers

// ...

list($controller, $action) = explode('#', $match['target']);
$controller = "routetest\\Controllers\\$controller";

$obj = new $controller();

It is possible through ::class , but this is already a little different

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question