Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

What the use of call_user_func and is_callable?

I haven't found many articles about such terms, can someone explain not-technically about call_user_func and is_callable?

1 Answer

Hi there, call_user_func() does the same thing like calling the function in your code, but at runtime. is_callable() checks if the function exists. Example:

<?php

function abc() {
    echo "Hello world!";
}

abc(); // You know the function name at development time and call it

call_user_func("abc"); // You only know the function name at runtime. Does the same as the above but is less efficient

is_callable("abc"); // Checks if the function exists. This evaluates to true

?>

In my opinion this leads to bad code style and I would never use this(if not totally necessary). I hope this is clear now! Best Regards, Philip

Thanks for the easy example. One question, if you are not using such functions, then might you have replaced this with the something else which is more optimum?

is_callable is like for future programming if we don't know the name of the function and just guessing?

I am a noob, so such reply you might be facing :D

Hi Vijesh, I don't really know why one would use these functions, but yes, they are used to call the functions at run time, which means that at the time of coding, you don't know what the functions name is and retrieve the function name e.g. by an input from the user. The better practice: You always know which functions to call at coding time, and solve these "problems" with other coding concepts as OOP, function parameters and such.

Please do not hesitate to ask me if there still is something you don't understand! :smiley: