Take variable from one function to another function within the same class?

Asked

Viewed 211 times

0

I need to capture the variable from one function to another function within the same class. Below follows example scope.

public function upPicture()
{
   $variavel = "Hello World!";            
}
public function cadastraPic() 
{
  print_r($variavel); //de dentro da função upPicture
}

Thanks for your help.

1 answer

2

Using only functions you can achieve this only if you return the desired value.

function upPicture(){
    $variavel = "Hello World!";
    return $variavel;
  }

function cadastraPic() {
   $variavel = upPicture();
   print_r($variavel); //de dentro da função upPicture
}

By programming object-oriented you can set a property in your class and method upPicture() arrow the value of this property for the method cadastraPic() can access it normally. See:

class MinhaClasse {
    protected $variavel;

    public function upPicture(){
        $this->variavel = "Hello World!";
      }

    public function cadastraPic() {
       print_r($this->variavel); //de dentro da função upPicture
    }
}

$classe = new MinhaClasse();
$classe->upPicture();
$classe->cadastraPic();

See this fiddle (On the page click on "Run-F9" to run it)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.