Stan Stan - 5 months ago 11
PHP Question

Passing variables between function is same class

Simple question but... I have two functions in my class. And I'm trying from first to send variables to second but can't get them..

class MyClass {

function one( $var1, $var2 ) {
...code
if(!$errors){
$url = 'http://example.com/b/'.$var1.'/c/'.$var2.'/p/';
} else { ... }
return true;

}

function two {

... some code...
echo $var2;
}
}


I've got Undefined $var2. Why?

Answer
class MyClass {
    private $var1;
    private $var2;
    function one( $var1, $var2 ) {
          $this->var1 = $var1;
          $this->var2 = $var2;
          ...code
        if(!$errors){
            $url = 'http://example.com/b/'.$this->var1.'/c/'.$this->var2.'/p/';                        
        } else { ... }
    return true;
    }
    function two() {
          ... some code...
          echo $this->var2;
   }
}

Store them as Class-Variables. Otherwise the rest of your class won't know about them.