函数定义顺序重要吗?
在下面的脚本中,声明项目的顺序重要吗?
例如,如果add_action指向一个尚未定义的函数?函数声明是否重要或者应该始终位于调用它的任何代码之前?
add_action('load-categories.php', 'my_admin_init');
function my_admin_init(){
//do something
}
In the script below, does the order in which items are declared matter?
For example, if the add_action points to a function that has not yet been defined? Does it matter or should the function declaration always precede any code in which its called?
add_action('load-categories.php', 'my_admin_init');
function my_admin_init(){
//do something
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
如果该函数是在调用之前或之后声明的,那并不重要,但该函数应该存在于脚本中并且应该被加载。
这是第一个方法,它将起作用:
这是第二个方法,也将起作用:
That doesn't matter if the function is declared before or after the call but the function should be there in the script and should be loaded in.
This is the first method and it will work:
This is the second method and will also work:
来自 PHP 手册:
然而,虽然这更多的是个人喜好,但我强烈建议将您实际使用的所有函数包含在外部
functions.php
文件中,然后使用require_once()
或include_once()
(根据喜好)位于主 PHP 文件的最顶部。这更符合逻辑——如果其他人正在阅读您的代码,那么很明显您正在使用自定义函数,并且它们位于functions.php
中。在我看来,省去了很多猜测。From the PHP manual:
However, while this is more of a personal preference, I would highly recommend including all the functions you actually use in an external
functions.php
file then using arequire_once()
orinclude_once()
(depending on tastes) at the very top of your main PHP file. This makes more logical sense -- if someone else is reading your code, it is blindingly obvious that you are using custom functions and they are located infunctions.php
. Saves a lot of guesswork IMO.您可以在定义之前调用函数,首先解析文件然后执行。
you can call a function before it's defined, the file is first parsed and then executed.
编号
这不是 C :P...
正如您在此处看到的,整个文件首先被解析,然后执行。
如果调用不存在的函数,php 将抛出错误。
No.
It is not C :P...
As you can see here , the whole file is first being parsed and then executed.
If a function that doesn't exist is being called, php will throw an error.
根据我个人的经验,在某些特殊情况下(例如,在函数中传递数组或在函数内传递函数等)。最好的选择是在调用上方定义函数。因此,有时函数不起作用,PHP 也不会抛出错误。
在正常的 php 函数中,这并不重要。您可以使用这两种类型。
As per my personal experience, In some special cases (Like, passing array's in function or function inside a function and so on). It's best option to define the function above the call. Because of this sometimes neither function works nor PHP throw an error.
In normal php functions, it doesn't matter. You can use both of the types.
没关系,只要在页面的某个地方声明即可。
如下所示:
http://codepad.org/aYbO7TYh
It does not matter, as long as it is declared somewhere on the page.
as seen here:
http://codepad.org/aYbO7TYh
引用用户定义函数手册部分:
因此,基本上:您可以在编写函数的定义之前调用它 - 但是,当然,当尝试调用函数时,PHP 必须能够看到该定义。
Quoting the User-defined functions section of the manual :
So, basically : you can call a function before its definition is written -- but, of course, PHP must be able to see that definition, when try to call it.