PHP Question

PHP: Fatal error: Call to undefined method ::(url)()

Whats wrong with my codes, I always got fatal error when I change my URL. I can't remove those if else below which have undefined, I will not get 2nd URL. I am beginner creating MVC please help

class event_trap
{
function __construct()
{
$url = $_GET['url'];
$url = rtrim($url. '/');
$url = explode('/', $url);
//print_r($url);

$file = 'event_mvc/controllers/' .$url[0] . '.php';
if (file_exists($file)) {
require $file;
} else {
require 'event_mvc/controllers/error.php';
$controller = new Error();
return false;
}

$controller = new $url[0];

if (isset($url[2])) {
$controller->{$url[1]}($url[2]); //<-- Undefined method
} else {
if(isset($url[1])) {
$controller -> {$url[1]}(); //<-- Undefined method
} else {

}
}
}
}


var_dump($url)

array (size=2)
0 => string 'event' (length=5)
1 => string '' (length=0)

Fatal error: Call to undefined method event::() in
C:\wamp\www\tabulation\event_mvc\libs\Bootstrap.php on line 33
Call Stack
# Time Memory Function Location
1 0.0004 142728 {main}( ) ..\event.php:0
2 0.0012 149096 event_trap->__construct( ) ..\event.php:4

Answer

Your variable $url is an array which you use to create an object and call methods with or without parameters. With the array ou have var_dumped 0=>event, 1=>'' you are creating an object of class event and call the method '' which does not exist. Correct your code or pass a valid function name.

You can try this which checks for empty string too.

if (isset($url[2]) && !empty($url[2]) {
    $controller->{$url[1]}($url[2]);
} else {
    if(isset($url[1]) && !empty($url[1]) {
        $controller -> {$url[1]}();
    }
}
Comments