| re: easy way of concatenating 2 strings
Kelvin Chu wrote:
[color=blue]
> Hi Group,
> Also, another question
>
> I tried making a function like so (just inline in the top of the php page):
>
> <?php
> $debug = "";
> function addDebug($text) {
> $debug = $debug . $text . "<br/>";
> echo $debug; // returns correctly
> }
> addDebug("blah");
> echo $debug; // not displayed properly
> ?>
>
> but it doesn't seem to work. Since I'm using php5, I thought everything is
> getting passed by reference now?[/color]
Well no - the problem is that it's NOT passed by reference. $debug is
not passed at all. You could modify the addDebug to accept $debug
passed by reference. That way, the contents of the memory location
pointed to by $debug will change.
function addDebug(\$debug, $text) {
$debug .= $text . "<br />";
}
$debug = "";
addDebug($debug, "foo");
addDebug($debug, "bar");
echo($debug);
Someone suggested using
global $debug;
This would also work - but it flies in the face of good programming
practice - as far as scoping variables etc.
The most elegant way would be to use a Class.
class Debug {
var $debug;
function add($text) {
$this->debug .= "$text<br />";
}
function out() {
echo $this->debug;
}
}
$odebug = new Debug;
$odebug->add("foo");
$odebug->add("bar");
$odebug->out();
Then again, you could just use the .= operator!
$debug = "";
$debug .= "foo<br />";
$debug .= "bar<br />";
echo ($debug);
Jamie |