声明为一种用途的函数有什么意义?

发布于 2024-10-01 12:31:06 字数 133 浏览 4 评论 0原文

我注意到在很多脚本(如 phpbb )中,一些函数在脚本顶部声明只是为了使用一次。这样做有什么意义呢?它们是用来使代码更具可读性吗?

例如,我有一个执行用户登录的页面,登录是可以在那里完成的操作。所以我声明了一个登录函数并在那里使用它。

I noticed in a lot of scripts ( like phpbb ) that some functions are declared on the top of the script just to be used once. What the point of doing that? Are they used to make the code more readable?

For example I have a page that execute the user login, and the login is an action that can be done just there. So I declare a function for the login and I use it there.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

始终不够 2024-10-08 12:31:06

是的,更具可读性通常是目标。有时,保留将来重新使用代码的选项。请记住,函数通常有点像黑匣子:如果您知道如何使用它,那么您并不真正关心它是如何工作的,因此它可以帮助程序员跟踪否则会是一长段代码的内容。

编辑:您的登录示例是一个很好的示例。您将来完全有可能希望从站点的其他位置登录,在这种情况下,将其作为功能是一个非常好的主意。此外,使用 login($username,$password) 比大量的数据库查找和 setcookie() 位要清晰得多。

Yes, more readable is usually the aim. And sometimes, to leave the option of re-using the code in future. Remember, a function is usually a bit of a black box: if you know how to use it, you don't really care how it works, so it can help the programmer keep track of what would otherwise be a long block of code.

Edit: your login example is a good one. It's entirely possible you'll want to login from somewhere else in your site in future, in which case, having it as a function is a very good idea. Also, having login($username,$password) is a lot clearer than a load of database lookup and setcookie() bits.

琉璃梦幻 2024-10-08 12:31:06

或许。而且您不知道该函数是否打算在将来的某个时候使用,甚至不知道它是否作为未来用户创建的扩展的基础。
但无论如何,当使用函数时,代码更有意义,因为你有一个小的“主”函数,你可以在其中调用其他小函数,而不是一个你无法理解任何东西的巨大的“主”函数。

Maybe. And you don't know whether that function is meant to be used some time in the future or even be a base for a future user-created extension.
But anyway, the code makes more sense when using functions, as you have a small "main" function within whom you call other small functions rather than a huge "main" where you can't understand anything.

你爱我像她 2024-10-08 12:31:06

与前面的答案非常相似,但是在函数中包含一段代码可以让您或其他人更容易地识别它、隔离它并随后将其包含在其他地方。

Much like the previous answers but having a block of code in a function leaves the door open to you or someone else more easily recognising it, isolating it and subsequently including it elsewhere.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文