Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a function before it is declared [duplicate]

Tags:

php

The following code runs in PHP

<?php

$foo = "Chocolate milkshake";

go($foo);

function go($param) {
    echo $param;
}

?>

// Output: chocolate milkshake

See this Demo http://codepad.viper-7.com/ToApZa

This code runs without errors and prints specified output, why? I thought this "function hoisting" only occurred in JavaScript

like image 220
Michael Coleman Avatar asked Nov 30 '14 08:11

Michael Coleman


People also ask

Can you call a function before you declare it?

However, functions go out of this route as they are read first, but only the function head (= first line). That is why function calls are possible before declaration.

Can I call a function before defining it in JavaScript?

With JavaScript functions, it is possible to call functions before actually writing the code for the function statement and they give a defined output. This property is called hoisting.

What happens if you define a function but do not call it?

A common error is defining a function but forgetting to call the function. A function does not automatically get executed. A function that does not explicitly return a value returns the JavaScript value undefined.

Is function call and function declaration same?

declare and define are the same, and they mean when you write all the code for your function. At that point the function just sits there doing nothing. call is when you tell the JavaScript interpreter to run the code in your function.


1 Answers

It doesn't matter where you declare your functions in PHP in most cases, as you've just proved :)

Take a look at this page for more details. The key point:

Functions need not be defined before they are referenced, except when a function is conditionally defined as shown in the two examples below.

like image 58
Ben Avatar answered Sep 23 '22 09:09

Ben