Calling a function before it's defined | PHP

一世执手 提交于 2019-11-27 03:16:40

问题


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? :)


回答1:


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.




回答2:


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




回答3:


You cannot call undefined function, it will raise a fatal error. although in procedural code it can be called and afterwards defined. As the script is first parsed then executed. includes don't matter, they behave as if they were written in the exact file.

there's no such thing as a variable "from a file". if the code defines the variable is not run, it can't be there.



来源:https://stackoverflow.com/questions/3559875/calling-a-function-before-its-defined-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!