简体   繁体   English

在PHP函数中访问全局变量

[英]Accessing global variables in PHP function

I'm new to php and I can't understand why is it that the variable "cons" isn't recognized by the the compiler when used inside the function "func", in the following code: 我是php的新手,我无法理解为什么在函数“func”中使用时,编译器无法识别变量“cons”,如下代码所示:

$cons = 1;

function plusCons($num) {
   return $num + $cons;
}

is it impossible to use global variables inside of a function's scope? 是不可能在函数范围内使用全局变量?

In order to access global variables within a PHP function, you need to use the global keyword to import the variable: 要在PHP函数中访问全局变量,您需要使用global关键字来导入变量:

$cons = 1;

function plusCons($num) {
   global $cons;

   return $num + $cons;
}

This also will work for you: 这也适合你:

$cons = 1;

function plusCons($num ,$cons) {
  return $num + $cons;
}

echo plusCons(2 , $cons); // this will output 3

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

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