在函数之外传递变量 php
我有一个检查表单验证的函数。如果出现错误,则有一个名为 $error 的变量。我如何使它在这个函数之外和本页的其余部分,无论是否在函数内部,都知道 $error 已设置?
但我不希望它转移到另一个页面。我知道存在全局性,但由于我在函数中启动 $error,我猜它在其他函数中不可用。
有什么想法吗?
I have a function that checks form validation. If there is an error then there is a variable called $error. How do I make it so outside of this function and the rest of this page regardless of inside of a function or not, know that $error is set?
I don't want it to carry over to another page though. I know there is global but since I am initiating the $error in a function I guess it is not available in other functions.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我会这样做
函数验证($form, &$errors)
{
// 设置 erros 变量的一些代码
返回假;
由于 $erros 是通过引用传递的,因此
该函数可以设置它的值。但变量本身仍然在调用代码的范围内。
I would make it this way
function validate($form, &$errors)
{
// some code that sets the erros variable
return false;
}
Since $erros is passed by reference, the function can set it's value. But the variable itself remains in the scope of the calling code.
如果您想通过 超级全局
$ 设置和使用全局变量GLOBALS
数组 PHP 手册:该数组随处可用。所以要小心。
If you want to set and use a global variable via the superglobal
$GLOBALS
array PHP Manual:That array is available everywhere. So take care.
我有一个表单类,其中包含一个记录错误的静态变量。例如:
然后要在验证函数中记录错误,您可以执行以下操作:
然后只需调用 parseErrors 即可吐出错误。请注意,这些只是片段。我实际上有一个与表单类交互的记录器类,对其进行了一些更改以进行整合。
我更喜欢做这样的事情而不是使用 GLOBALS,使用 GLOBALS 或 SESSION 会很快变得混乱,这是另一种选择。
I have a form class with a static variable inside of it that logs errors. For example:
Then to log errors from within your validation functions, you can do something like this:
Then just call the parseErrors to spit out your errors. Please note these are just snippets. I actually have a logger class that interacts with the form class, changed it up some for consolidation.
I prefer doing things like this than using GLOBALS, it can get messy really quick using GLOBALS or the SESSION for that matter, which is another option.
我宁愿返回它,并检查它的 count() (我通常将错误放入数组中)。如果是> 0则有错误,否则无错误。
I'd rather return it, and checks its count() (I usually put errors in array). If it's > 0 then there are errors, otherwise there are no.