0

Thanks for your time in advance. I am a newbie in php and encountered a strange problem, at least for me it is strange. It is about showing variable in string template. Please see the code below:

public function welcome() {
    $data="everyone";
    $b = $this->returnTemplate();
    $a = "<div>dear $data</div>";
}
public function returnTemplate()
{
    return "<div>dear $data</div>";
}

I just thought both $a and $b should be the same value <div>dear everyone</div> but in fact only $a is while $b is <div>dear </div>. That really puzzled me and I wonder why? Could someone please to explain it to me?

Thanks in advance and any feedback is welcome!

Rang-ji Hu
  • 121
  • 1
  • 9
  • 3
    It's called [variable scope](http://www.php.net/manual/en/language.variables.scope.php), and it's fully documented – Mark Baker Aug 19 '15 at 15:05

3 Answers3

1

You are encountering 'variable scope'. As you have defined the variable $data in the welcome() function, it will not be available anywhere outside of that function. To overcome this, either move it out of the function OR pass it as a parameter to the returnTemplate function.

More info: http://php.net/manual/en/language.variables.scope.php

mfisher91
  • 805
  • 1
  • 8
  • 23
0
public function welcome() {
 $data="everyone";
 $b = $this->returnTemplate($data);
 $a = "<div>dear $data</div>";
}
public function returnTemplate($data)
{
  return "<div>dear $data</div>";
}

this works.

http://php.net/manual/en/language.variables.scope.php

messerbill
  • 5,499
  • 1
  • 27
  • 38
0

Like already mentioned, you are trying to breach the variable scope. In other words you are trying to use a local variable out of its scope (the function you have initially declared/defined in). There are two ways to achieve what you are trying:

1) Pass the variable as a parameter to the function and then use the returned value, something like this:

public function welcome() {
 $data="everyone";
 $b = $this->returnTemplate($data);
 $a = "<div>dear $data</div>";
}
public function returnTemplate($data)
{
  return "<div>dear $data</div>";
}

2) Declare the variable as GLOBAL on the top/start. So it will have a scope out of that particular function and achieve exactly what you are trying to.

DirtyBit
  • 16,613
  • 4
  • 34
  • 55