Fabian
Fabian

Reputation: 3495

function_exists returns false every time

I'm trying to check whether a function exists or not but I keep getting false in my if

I try to call the function like this, where $function is the function name:

if (function_exists($this->module->$function))
{
    $this->module->$function($vars);
}
else
{
    echo 'no';
}

The variable module is defined as the class where the function should be called:

$this->module = $module;
$this->module = new $this -> module;

Am I missing something here? Thank you!

Upvotes: 3

Views: 3025

Answers (5)

Willem Mulder
Willem Mulder

Reputation: 13994

function_exists() expects a String as parameter. This will do the trick:

method_exists($this->module, $function);

Good luck!

Upvotes: 2

Greg
Greg

Reputation: 21899

function_exists takes the name of a function as a string, and has no concept of class hierarchy.

If $function is the name of the function, simply use this code:

if(function_exists($function)) {
    // Call $function().
}

However, looking at your code it looks more like you want to detect if a method of an object exists.

method_exists takes two parameters, 1: the object to test on, 2: the name of the method to detect.

if(method_exists($this->module, $function)) {
    $this->module->$function($vars);
}

Upvotes: 2

Aleks G
Aleks G

Reputation: 57306

You need to check whether method exists and not the function:

if (method_exists($this->module, $function))
{
    $this->module->$function($vars);
}
else
{
    echo 'no';
}

Have a look at the documentation: http://php.net/manual/en/function.method-exists.php

Upvotes: 2

Aron Rotteveel
Aron Rotteveel

Reputation: 83163

You need to use method_exists():

if (method_exists($this->module, $function)) {
    // do stuff
}

Upvotes: 3

Fabian
Fabian

Reputation: 3495

Just could figure it out: Using method_exists() solved my problem

method_exists($this->module,$function)

I answered this question on my own for people who may have the same problem!

Upvotes: 4

Related Questions