Function_exists returns false every time

I am trying to check if a function exists or not, but I keep getting false in my if

I am trying to call a function like this where $ function is the name of the function :

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

      

A variable is module

defined as the class in which the function should be called:

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

      

Am I missing something? Thank!

+3


source to share


5 answers


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

method_exists($this->module,$function)

      



I answered this question myself for people who might have the same problem!

+3


source


You need to use method_exists()

:



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

      

+2


source


You need to check if a method exists and not a 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

+2


source


function_exists

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

If $function

is the name of the function, just use this code:

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

      

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

method_exists

takes two parameters: 1: object to test, 2: method name to discover.

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

      

+2


source


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

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

      

Good luck!

+1


source







All Articles