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 trialammarkhan
Front End Web Development Techdegree Student 21,661 PointsHow does a function can be called without set of ()
I am confused over how do we call on a function without set of () , in the video the call to function is done by
$func = answer;
echo $func ;
Whereas i what i know is that a function is called like
$func = answer();
echo $func;
So why is the video other way around without ()
2 Answers
David Makowski
13,676 PointsIn the second version the parenthesis are kind of included in the $func variable. So after that it's possible to call it without them, because what you are actually calling when you write
echo $func;
is answer()
Hugo Paz
15,622 PointsHi Ammar,
If you notice in the video, he uses parenthesis on the variable, like this:
$func = 'answer';
$func();
ammarkhan
Front End Web Development Techdegree Student 21,661 PointsBut why not just use
$func();
for all of the time < php 4, i been seeing like that of echo out function, but '''php $function = 'answer'; $function(); '''' what's the difference and why use one over the other?
Hugo Paz
15,622 PointsYou use a variable with the name of a function.
Here's an example:
<?php
function printName($name){
echo $name . '<br/>';
}
$name = 'Hugo';
//I gave a different variable name in this case to make it clear what this variable is. We pass it the name of the function as a string.
$printFunction = 'printName';
//We use the variable to call the printName function
$printFunction('Ted');
printName($name);
?>
Dan Avramescu
11,286 PointsDan Avramescu
11,286 Pointsi think the $func here acts as a callback for echo, correct me if i'm wrong