My code:
$myText = "";
function addText($textString){
$myText .= $textString;
}
addText("Hello there...");
echo $myText;
Expected output:
Hello There...
$myText was empty.
Why does this happen?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With