PDA

View Full Version : Resolved echo method + static method



ggalan
05-29-2011, 02:00 AM
i am trying to echo some strings like this


$about = new Model_About();
echo $about->beforeHeader() . ' + ' . Model_About::sFunc();

but it outputs this: string before headerstatic string +
why does this output in the end?


. ' + ' .

class


class Model_About
{
private $str = 'string before header';
private static $statStr = 'static string';

function beforeHeader()
{
echo $this->str;
}
static function sFunc()
{
echo self::$statStr;
}
}

traq
05-29-2011, 04:56 AM
because of the order you're doing things in. when this
echo $about->beforeHeader() . ' + ' . Model_About::sFunc();
// I'll refer to this line as "the call" in my explanationis executed, things happen in this order:

1) beforeHeader() runs. it echos $str to the browser. it has no return value, so we end up with this:
--browser output: "string before header"
--"the call" value: ""

2) once the function is done, the spaces and plus sign are concatenated to the value that the call will echo (in fact, as you'll see, this is the only value that "the call" will echo):
--browser output: "string before header"
--"the call" value: " + "

3) sFunc() runs. it echos $statStr, but like the first function, has no return value:
--browser output: "string before headerstatic string"
--"the call" value: " + "

4) now we're at the end of the statement, so the value of "the call" is echoed:
--browser output: "string before headerstatic string + "

And that is that.

When you start using functions, classes, etc., in more complex ways, it is far more useful to return values rather than echoing them. Once you have a complete result from your script, echo it all at once.
$about = new Model_About();

echo $about->beforeHeader() . ' + ' . Model_About::sFunc();
// outputs: "string before header + static string"

// you could also do this (same result):
// $printthis = $about->beforeHeader() . ' + ' . Model_About::sFunc();
// echo $printthis;

class Model_About
{
private $str = 'string before header';
private static $statStr = 'static string';

function beforeHeader()
{
return $this->str;
// note: "return", NOT "echo"!
}
static function sFunc()
{
return self::$statStr;
}
}