将全局变量和参数传递给 PHP 中的函数
您好,感谢您的光临,
我想将变量 ($user
) 从前一个函数传递到另一个函数,但我需要使用新函数的参数来传递将要执行的值渲染这个新的。
有什么方法可以将变量从另一个函数传递到一个只需要三个参数的新函数,并且它们都不是前一个函数中的变量?
示例:
function my_function($country, $age, $colour) {
if ($user = true) {
echo "User is from " . $country . " and " . $age . " and his favourite colour is " . $colour;
}
}
my_function("italy", 19, "red");
如果我将 my_function: 放入函数内部,它会起作用,
global $user;
但我相信使用全局变量不是一个好的做法。
关于如何将其作为参数传递的任何想法?我是否应该将其添加为新函数参数中 $colour
之后的另一个变量?
非常感谢您的帮助:)
Hello and thanks for being there,
I would like to pass a variable ($user
) from a previous function to another one, but I need to use the arguments of the new function to pass the values that will render this new one.
Is there any way I can pass a variable from another function to a new function that only expects three arguments, and none of them is the variable from the previous function?
Example:
function my_function($country, $age, $colour) {
if ($user = true) {
echo "User is from " . $country . " and " . $age . " and his favourite colour is " . $colour;
}
}
my_function("italy", 19, "red");
It works if I put inside function my_function:
global $user;
but I believe using global variables is not a good practice.
Any idea on how to pass it as an argument? Should I just add it as another variable after $colour
in the arguments of the new function?
Thanks a lot for your help :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以将其作为参数传递,或者更好地这样做:
因为您不必在该函数内使用
$user
变量。You can pass it as an argument, or better do this:
since you don't have to use the
$user
variable inside that function.您可以使用此函数,但最佳实践是使用类。
即如果你调用 my_function("italy", 19, "red"), $user 默认为 false
You can use this function but best practice will be using class.
i .e if you call my_function("italy", 19, "red"), $user will be false by default
好吧,全局变量是一种不好的做法,但在您的情况下是可行的。
我绝对会建议您研究/使用面向对象的方法。
确实有很多不同的方法可以实现您的尝试。
一种方法是将代码封装到对象中。
或者您可以实现单例模式,以便从任何地方轻松访问您的对象/函数。
Well, global variables are a bad practice, but a viable one in your case.
I would definitely recommend you looking into/using a Object Oriented approached.
There are really a bunch of different ways to achieve what your trying.
One way would be to encapsulate your code into a object.
Or you could implement a Singleton Pattern to easily get access to your object/functions from anywhere.
如果你以前的函数是这样的:
你可以这样调用它:
If your previous function is something like this:
You can call it like this: