tags:

views:

118

answers:

3

I'm just starting with Object Oriented PHP and I have the following issue:

I have a class that contains a function that contains a certain script. I need to call a variable located in that script within another function further down the same class.

For example:

class helloWorld {

function sayHello() {
     echo "Hello";
     $var = "World";
}

function sayWorld() {
     echo $var;
}


}

in the above example I want to call $var which is a variable that was defined inside a previous function. This doesn't work though, so how can I do this?

A: 

I do not know php all that well, but there are a couple of ways. You should be able to declare a global variable then you should be able to access it. You also should be able to pass variables to functions.

John
+5  A: 

you should create the var in the class, not in the function, because when the function end the variable will be unset (due to functoin termination)...

class helloWorld {

private $var;

function sayHello() {
     echo "Hello";
     $this->var = "World";
}

function sayWorld() {
     echo $this->var;
}


}
?>

If you declare the Variable as public, it's accessible directly by all the others classes, whereas if you declare the variable as private, it's accessible only in the same class..

<?php
 Class First {
  private $a;
  public $b;

  public function create(){
    $this->a=1; //no problem
    $thia->b=2; //no problem
  }

  public function geta(){
    return $this->a;
  }
  private function getb(){
    return $this->b;
  }
 }

 Class Second{

  function test(){
    $a=new First; //create object $a that is a First Class.
    $a->create(); // call the public function create..
    echo $a->b; //ok in the class the var is public and it's accessible by everywhere
    echo $a->a; //problem in hte class the var is private
    echo $a->geta(); //ok the A value from class is get through the public function, the value $a in the class is not dicrectly accessible
    echo $a->getb(); //error the getb function is private and it's accessible only from inside the class
  }
}
?>
Marcx
Thank you very much for the detailed explanation.
Sam
A: 

Make $var a class variable:

class HelloWorld {

    var $var;

    function sayHello() {
        echo "Hello";
        $this->var = "World";
    }

    function sayWorld() {
        echo $this->var;
    }

}

I would avoid making it a global, unless a lot of other code needs to access it; if it's just something that's to be used within the same class, then that's the perfect candidate for a class member.

If your sayHello() method was subsequently calling sayWorld(), then an alternative would be to pass the argument to that method.

Rob