PHP函数调用放置 [英] PHP Function Call Placement

查看:49
本文介绍了PHP函数调用放置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码段:

function f() {
    return 'hi';
}

echo f();

对比此片段:

echo f();

function f() {
    return 'hi';
}

当我运行脚本时,它们都产生相同的结果.太好了.

When I run the scripts, they both produce the same results. That's great.

但是我的问题是(并且在任何搜索中都找不到很好的答案或参考),在定义函数之前可以调用该函数(即,从脚本文件的顺序分析角度来看)吗?

But my question is (and I could not find a good answer or reference in any of my searches), is it okay to call the function before it is defined (ie, from a sequential parsing of the script file perspective)?

如果我将函数调用放在脚本文件中的函数定义块的前面,我不想遇到任何问题或弃用.

I don't want to run into any issues or deprecation down the road if I leave the function call ahead of the function definition block in my script file.

推荐答案

来自

功能不需要在之前定义 它们被引用,除非当 功能被有条件地定义为 在下面的两个示例中显示.

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

在定义函数之前调用(引用)函数是一种PHP的有意功能,我认为您不必担心它会被弃用.

The possibility to call (reference) a function before it is defined is a PHP intentional feature and I don't think you need to worry about it becoming deprecated.

作为一种观察,如果您可以在函数之前或之后进行声明,那么在使用该函数之前先声明它是常识.

As an observation, if you can choose from declaring the function before or after, it would be common sense to declare it before it's used.

注意:由于该函数仅在运行环境中定义,因此以下代码将产生致命错误.

Note: The following code will give a fatal error because the function will only be defined at run rime.

<?php
echo helloWorld();
if(1){
    function helloWorld() {
        return 'hello world';
    }
}
?>

这篇关于PHP函数调用放置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆