user1810078
user1810078

Reputation: 19

Fatal error: Method name must be a string

I'm getting error:

Fatal error: Method name must be a string in C:\xampp\htdocs\index.php on line 15"

LINE 15:

$obj = new $url[0]();

CODE:

<?php
error_reporting(E_ALL ^ E_NOTICE);

$url = $_GET['url'];
$url = explode('/', $url);

if (!file_exists('controllers/' . $url[0] . '.php')) {
    $url[0] = 'error';   // error kontroleris 
}    
require 'controllers/' . $url[0] . '.php';

$obj = new $url[0]();
$obj->$url[1]();

BTW.: Script is not finished yet.

Upvotes: 0

Views: 1819

Answers (2)

Samuel Cook
Samuel Cook

Reputation: 16828

$_GET['url'] = 'foo/bar'; // temp set $_GET
$url = $_GET['url'];
$url = explode('/', $url);

if (file_exists('controllers/' . $url[0] . '.php')){
    require 'controllers/' . $url[0] . '.php';
}else{
    $url[0] = 'error'; 
}

$obj = new URL;
if(method_exists($obj,$url[0])){ // test that method exists
    echo $obj->$url[0](); // or whatever your handling may be
}

class URL{
    public function error(){
        $return = 'this is for the error handling';
        return $return;
    }
}

Upvotes: 0

raina77ow
raina77ow

Reputation: 106385

Actually, this syntax:

$urls = array('DOMDocument');
$dom = new $urls[0]('');
var_dump( $dom );

... is valid even in PHP 5.2 (proof). But this line...

$obj->$url[1]();

... is pretty damn able (another proof) to throw exactly the same error as you've shown, as you don't check for url array length anywhere in your code.

Upvotes: 2

Related Questions