Q:

PHP function to add data to string

My code:
$myText = "";

function addText($textString){
   $myText .= $textString;
}

addText("Hello there...");

echo $myText;

Expected output:

Hello There...

$myText was empty.
Why does this happen?

A:

You need to tell the function to use the global variable $myText
function addText($textString){
   global $myText;
   $myText .= $textString;
}

Though using global variables within functions is considered harmful.

A:

try this:
$myText = "";

function addText($textString){
   global $myText;
   $myText .= $textString;
}

addText("Hello there...");

echo $myText;

the reason you have to do the is is bc $myText is not in the scope on the function. so to put it in scope, you have to tell the function which global variables to use
here is the demo: http://codepad.org/DeH89No6

A:

Ok let me actually help you as opposed to just telling you how to get your current example to work. Basically, variables defined outside a custom function are not visible inside it. In your example your function has no idea what $myText is because it was declared out side of the functions scope. To pass variables to a function you will need to add them as parameters - the variables you pass with a function when you define and then when you call it, eg: function addText($param1, $param2).
As other have mentioned, you can allow functions to see certain variables by using the global keyword, but only really use this for abstract things like database connections, not the actually data you want to configure, do all that inside your function.
Hopefully this will help you understand PHP a bit more.

