开发者

In PHP: How to call a $variable inside one function that was defined previously inside another function?

开发者 https://www.devze.com 2022-12-23 19:46 出处:网络
I\'m just starting with Object Oriented PHP and I have the following issue: I have a class that contai开发者_JS百科ns a function that contains a certain script. I need to call a variable located in t

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

I have a class that contai开发者_JS百科ns 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?


you should create the var in the class, not in the function, because when the function end the variable will be unset (due to function 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
  }
}
?>


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号