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

Doug Tr
Doug Tr
140 Points

variable function vs named function?

Can someone please explain to me what is the purpose of using 2 (variable function) over 1 (named function)?

1.
function add ($a, $b) {
         return $a + $b;
}
add();

2.
 function something ($a, $b) {
         return $a + $b;
}
$add = 'something';
$add();

1 Answer

Nathan Heffley
Nathan Heffley
19,878 Points

The purpose of variable functions like 2 is to add flexibility. In your example there isn't really a reason.

function example_1() {
    echo "One";
}

function example_2() {
    echo "Two";
}

function example_3() {
    echo "Three";
}

$counter = 1;
while ($counter < 4) {
    $function = "example_" . $counter;
    $function();
    $counter += 1;
}

In this example the code will first run example_1() and then example_2() and then example_3().

It just gives flexibility.