简体   繁体   English

如何在php中的函数中分配全局变量值?

[英]How to assign global variable value in a function in php?

i need to assign a global variable value by passing it in a function, something like static variable i guess.我需要通过将它传递到一个函数中来分配一个全局变量值,我猜想像静态变量一样。 Here is my code这是我的代码

<?php

//this is old value
$var = "Old Value";

//need to change the value of global variable
assignNewValue($var);
echo $var;

function assignNewValue($data) {
    $data = "New value";
}
?>

After the execution the value of var need to be New Value.执行后 var 的值需要为 New Value。 Thanks in advance.提前致谢。

<?php

//this is old value
$var = "Old Value";

//need to change the value of global variable
assignNewValue($var);
echo $var;

function assignNewValue(&$data) {
    $data = "New value";
}
?>

I made the argument of assignNewValue a reference to the variable, instead of a copy, with the & syntax.我使用&语法将 assignNewValue 的参数作为对变量的引用,而不是副本。

You can try it in 2 ways, the first:您可以通过两种方式尝试,第一种:

// global scope
$var = "Old Value";

function assignNewValue($data) {
   global $var;
   $var = "New value";
}

function someOtherFunction(){
    global $var;
    assignNewValue("bla bla bla");
}

or using $GLOBALS : (oficial PHP's documentation: http://php.net/manual/pt_BR/reserved.variables.globals.php )或使用$GLOBALS :(官方 PHP 文档: http : //php.net/manual/pt_BR/reserved.variables.globals.php

function foo(){
  $GLOBALS['your_var'] = 'your_var';
}
function bar(){
  echo $GLOBALS['your_var'];
}
foo();
bar();

Take a look: Declaring a global variable inside a function看一看: 在函数内部声明一个全局变量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM