Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

PHP PHP Functions Function Returns and More PHP Variable Functions

How 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

In 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()

Dan Avramescu
Dan Avramescu
11,286 Points

i think the $func here acts as a callback for echo, correct me if i'm wrong

Hugo Paz
Hugo Paz
15,620 Points

Hi Ammar,

If you notice in the video, he uses parenthesis on the variable, like this:

$func = 'answer';

$func();

But 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
Hugo Paz
15,620 Points

You 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);

?>