0

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:

$cons = 1;

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

is it impossible to use global variables inside of a function's scope?

3
  • 2
    declare it global $cons; inside function. See: php.net/manual/en/language.variables.scope.php Commented Dec 13, 2012 at 12:51
  • 4
    function plusCons($num) use($cons) { ... Commented Dec 13, 2012 at 12:52
  • 1
    You can, but it generally should be avoided. You should just pass the variable in as a parameter and then update it when the function returns, or use a class. Commented Dec 13, 2012 at 12:56

2 Answers 2

3

In order to access global variables within a PHP function, you need to use the global keyword to import the variable:

$cons = 1;

function plusCons($num) {
   global $cons;

   return $num + $cons;
}
Sign up to request clarification or add additional context in comments.

2 Comments

this will not work in a lot of contexts, e.g. assiging a closure to a variable inside a class method. Use use(...).
Right. Fortunately that isn't what the OP was inquiring about.
0

This also will work for you:

$cons = 1;

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.