-2

I have declared a variable protected in my class, then I assign a value to the variable in my first function. And then I want to use that same variable, with its value in another function. But is not working, can anyone tell me what I'm doing wrong or if it is possible at all to do this or how it could be done. Here is some example of my code:

class Forecast {
   protected $myStream;

   public function ajaxForecast() {
      $myStream = $GET_["selectedStream"];
      return json_enconde($myStream);
   }

   public function show() {
      echo $myStream;
   }

}
3
  • 1
    What do you mean by not working? Dec 19, 2012 at 10:41
  • It's $_GET, not $GET_. And you must use $this->.
    – Damien
    Dec 19, 2012 at 10:53
  • What I mean is that I don't get anything from the echo on my show() function. And yes, sorry the $GET_ was a typo, I have it right $_GET. The return json_encode part works.
    – Probandot
    Dec 19, 2012 at 11:17

3 Answers 3

4

You should use

class Forecast {
    protected $myStream;

    public function ajaxForecast() {
        $this->myStream = $_GET["selectedStream"];
        return json_encode($this->myStream);
    }

    public function show() {
        echo $this->myStream;
    }
}

Always use $this statement within classes.

1
  • Well ennovativemedia, I really appreciate your answer and makes sense to me, but it is not working on my project. I don't know if it is because I'm working on typo3 and might have its own way of doing things or what it is the reason I can't echo myStream on show().
    – Probandot
    Dec 21, 2012 at 9:05
0

I strongly advice you to read the manual.

Use it like this

public function Show() { 
   echo $this->myStream;
   // or use return $this->myStream
}
0
0

You are not using the $this keyword. So you are creating a new local variable $myStream, not assigning a value to your instance field like you think you are. The scope of $myStream is limited to the function ajaxForecast and is not available outside of that. The scope of $this->myStream is within the object itself (and any subclasses).

public function ajaxForecast() {
    $this->myStream = $GET_["selectedStream"];
    return json_enconde($myStream);
}

From php.net

The pseudo-variable $this is available when a method is called from within an object context. $this is a reference to the calling object (usually the object to which the method belongs, but possibly another object, if the method is called statically from the context of a secondary object).

Docs on php oop here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.