Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 243
Dave Avatar asked Jul 27 '26 22:07

Dave


2 Answers

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.

like image 158
Ólafur Waage Avatar answered Jul 31 '26 16:07

Ólafur Waage


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

like image 35
Naftali Avatar answered Jul 31 '26 16:07

Naftali



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!