0

I getting a php error

undefined variable $fname

 $fname="John";
 function getThis()
 { 
  $complete_name= $fname."Kerry";
echo $complete_name;}
    getThis();  

Any help in the right direction is much appriciated! Thanks

3
  • 1
    use global keyword for $fname Commented Mar 13, 2015 at 7:20
  • 1
    Variable scoping issue most likely Commented Mar 13, 2015 at 7:21
  • yes, it's about scoping, I admit it. otherwise, you have other related codes with it? Commented Mar 13, 2015 at 7:29

6 Answers 6

2

you have a variable scoping issue

Variables defined outside the function have Global scope and they can not be used inside a function, If you want to use them inside a function You must write the global keyword before the variable name.

 global $fname;

And in your case

I noticed that Variable $fname is defined outside the function, and it has a global scope, if you use this inside the function ,then it will throw error.

Try this

  $fname="John";
  function getThis()
 { global $fname;
  $complete_name= $fname."Kerry";
echo $complete_name;}
    getThis();  

Source :

http://php.net/manual/en/language.variables.scope.php

Sign up to request clarification or add additional context in comments.

Comments

1

Try to place the $fname inside the getThis() function, as in:

<?php

 function getThis() { 
 $fname="John";
 $complete_name= $fname."Kerry";
 echo $complete_name;
 }
 getThis();

?> 

Comments

1

Use This :-

$fname="John";

    function getThis()
     { 
    global $fname;
    $complete_name= $fname."Kerry";
    echo $complete_name;
    }
    getThis();

For more information click here

Comments

1

You could pass the variable into the function.

Like so:

 $fname="John";

 function getThis($f_name)
 { 
   $complete_name= $f_name."Kerry";

   echo $complete_name;
 }

 getThis($fname); 

Comments

0

You can not access variables inside function which declared out side, you have to use global keyword to use....

 $fname="John";
 function getThis()
 { 
global $fname;
$complete_name= $fname."Kerry";
echo $complete_name;}
    getThis(); 

1 Comment

Maybe just add comment as to what was changed and why.
-1

You have to declare $fname as global. That's it...

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.