[英]How do I make a variable from outside a function work in that function?
function nothing() {
echo $variableThatIWant;
}
The better way is to pass it as an argument. 更好的方法是将其作为参数传递。
function nothing($var) {
echo $var;
}
$foo = 'foo';
nothing($foo);
The evil way, and I dont know why I'm even showing you this, is to use global. 我什至不知道为什么还要向您展示这个邪恶的方法,就是使用global。
function nothing() {
global $foo;
echo $foo;
}
$foo = 'foo';
nothing();
You can put "global" before the variable you want to use, Like this : 您可以将“ global”放在要使用的变量之前,如下所示:
<?php
$txt = "Hello";
function Test() {
global $txt;
echo $txt;
}
Test();
?>
OR : you can passed it as parameter, Like this : OR:您可以将其作为参数传递,如下所示:
<?php
$txt = "Hello";
function Test($txt) {
echo $txt;
}
Test($txt);
?>
source : http://browse-tutorials.com/tutorial/php-global-variables 来源: http : //browse-tutorials.com/tutorial/php-global-variables
You have to use global
. 您必须使用
global
。
$var = 'hello';
function myprint()
{
global $var;
echo $var;
}
You can also use a class property (or member variable) if you are inside a class: 如果您在类内部,也可以使用类属性 (或成员变量):
<?php
$myClass = new MyClass();
echo $myClass->nothing();
class MyClass {
var $variableThatIWant = "something that I want";
function nothing() {
echo $this->variableThatIWant;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.