Is there a way to check if a function exists within a class?

I’m passing some post data to execute a function based on post data, to determine if this should execute I’ve tried to use the following:

$SP = new StoredProcedure();

if(function_exists($SP->$_POST['function']))
{
    $SP->$_POST['function']();
}
else
{
    echo 'function does not exist.';
}

Unfortunately this passes the following error:

Notice: Undefined property: StoredProcedure::$getFormList in
C:\DWASFiles\Sites\junglegym\VirtualDirectory0\site\wwwroot\wp-content\plugins\qcore\qcore_waitress.php
on line 353 function does not exist.

I’m certain this function does exist, and when I execute it without the function_exists()

Is there a way to check if a function exists when it’s inside a class?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

method_exists checks for method of a class for a given object:

Docs Link:
http://www.php.net/method_exists

if(method_exists($SP, $_POST['function'])) {
    {
        $SP->$_POST['function']();
    }
    else
    {
        echo 'function does not exist.';
    }

function_exists() and method_exists() are for these checks. First is for regular functions and second for OOP functions.

Solution 2

You should use method_exists

Try with:

if(method_exists($SP, $_POST['function'])) {

Solution 3

check this all

Find out if a method exists in a static class

Checking if function exists

and also PHP manual at

php.net/method_exists

php.net/manual/en/function.function-exists.php

www.php.net/class_exists

Hope these might help you.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply