Peter Elzinga
Peter Elzinga

Reputation: 125

Checking if function exists

I got an problem with checking i a function exists - i know function_exists() and method_exists() but cannot get the functionality i look for

I pass functions through a socket connection like $MM->Player->Play(). After that i eval them and return the result through the socket connection.

I do filter the functions (have to start with $MM, anything else will be rejected), but i cant get my code to check if the function exists. This is important because the server will crash if the function does not exists.

Anyone know a solution for this??

Thanks in advance.

the code:

$MM = new SDBApplication;

In the constructor of SDBApplication:

$this->Player = new SDBPlayer;

I tried the following methods to check: the code:

method_exists($MM, "Player::Play"); function_exist("$MM->Player->Play);

both return false even though the function exists

The solution

$parts = explode('->', $string);
$numParts = count($parts)-1;
$object = '$MM';
for($i=0; $i < $numParts; $i++){
    $object .= '->'.$parts[$i];
}
$parts[$numParts+1] = preg_replace('(\\(.*\\))', '', $parts[$numParts]);
eval( '$check = method_exists('.$object.', '.$parts[$numParts+1].');');

It needs to be eval'd because the input is a string.

Upvotes: 1

Views: 5643

Answers (2)

BenOfTheNorth
BenOfTheNorth

Reputation: 2872

Try it this way around in your constructor of SDBApplication

method_exists($this->Player, 'Play');

Upvotes: 6

kingmaple
kingmaple

Reputation: 4310

function_exists() and method_exists() are for this type of checks. First is for regular functions and second for OOP functions.

Upvotes: 2

Related Questions