简体   繁体   中英

Is it possible to access variables without putting “global” in front of them in functions?

My code is much more complex than this, but here's the just of it:

$string = "wuddup";

function echothis() {
echo $string;
}

echothis();

Is there an easy way to do this without saying global $string ?

Reason being, I have a check login function, with many variables and I have config variables outside the function...

Whatever happened to parameters?

function echothis($str) {
    echo $str;
}

echothis($string);

If you are having issues with managing variables and their scope, chances are you need to refactor your code structure.

Just Create a class and add static variables to it. You can access it from any where without creating an instance of the class.

class base2 {
public static $var2 = 1;

}

Refer it as below

echo base2::$var2;

You could have your function take in the variables as arguments or perhaps an array containing all these arguments.

$all_variables = array(
  "string" => "wuddup",
  "number" => 6,
  "an_array" => array(1, 3, 4)
);

function example_func($args) {
  // does things
}

example_func($all_variables);

Alternatively, you could create a class and reference the variables through $this .

您可以将配置变量定义为常量,然后在函数内部调用它们。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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