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

I am just starting out with object oriented PHP and I have the following problem:

I have a class containing a function containing a specific script. I need to call a variable located in this script in another function further in the same class.

For instance:

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 the previous function. This does not work, but how can I do it?

+3
source share
2 answers

you have to create var in the class, not in the function, because when the function ends, the variable will be disabled (due to termination of the function) ...

class helloWorld {

private $var;

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

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


}
?>

public, , private, .

<?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 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 accessible only from inside the class
  }
}
?>
+17

$var :

class HelloWorld {

    var $var;

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

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

}

, ; -, , .

sayHello() sayWorld(), .

0

Source: https://habr.com/ru/post/1737823/


All Articles