Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a function before it's defined | PHP

Tags:

php

Is there any possible way when in one file - please note, just one file. To call a function when it isn't defined yet, e.g.

<?php

echo global_title();

function global_title()
{
    $title = $_GET['name'];

    return $title;
}

?>

I don't know how to explain this, but it's not quite possible isn't it? What about variable from another file (without including it) can be called in a different file, e.g.

config.php

<?php

$db = "localhost";

?> 

index.php

<?php

// I do not want it to be accessed by including it or using sessions

echo $db;

?>

Know what I mean? :)

like image 522
MacMac Avatar asked Aug 24 '10 18:08

MacMac


2 Answers

You can call a function which is defined after calling it. That's because PHP first parses the file and then executes it.

As for the variable - this is not possible, you have to include the file.

like image 131
bisko Avatar answered Oct 06 '22 00:10

bisko


I just discovered that you can call a function if it's defined later in the same file.
But if it's defined in an other file, you must include the file before calling the function.

my_func();
function my_func() {...}
--->   No problem

but

my_func();
include_once 'define_my_func.php';
--->   PHP Fatal error

It's like a conditional function as in the example 2 on the doc on user-defined functions

like image 27
lolesque Avatar answered Oct 06 '22 00:10

lolesque