function exists and execute it
hi guys i wanna ask u i have a class and i wanna check a function inside my class if exist then execute it with method dynamically
My Code :
foreach ($this->functions[substr($this->tram, 6, 2)]['function'] as $key => $value){
if(function_exists($key)) {
$key(); //not working
}
else {
echo " Les fonction ".$key." ne sont pas disponibles.<br />\n";
}
}
}
Hello, here $key is only a string.
Have you tried to use call_user_func() php function ?
@russelmhardy You can simply try this-
public function foo()
{
dd("I am calling");
}
public function bar()
{
$key = 'foo';
if(function_exists($key())) {
$key();
}
}
@tisuchi That's what he has tried no ? ;)
@vincent15000
I think he checked the function without ().
function_exists($key)
But I suggest this-
function_exists($key())
@tisuchi Oh yes, exactly, I didn't notice.
@russelmhardy
Probably the most proper way is using the curly brackets {$key}()?
if(function_exists({$key}())) {
@tisuchi I don't know this notation in this context. Curly brackets are often used to write a variable directly in another string.
$string = 'Hello {$my_variable}, how are you ?';
@vincent15000 I agree with you.
But I believe {} is also used to wrap your variable when you call it from the string.
Thanks Guys
i slove It By $this->{$key}();
@MichalOravec What difference between method_exists() and function_exists() ?
@vincent15000
function_exists checks global functions.
method_exists checks methods (functions) in the class.
Please or to participate in this conversation.