-1

I have two functions in a class. What i need is something like this (This is incorrect)

class Home{

    function one(){
        $var1 = "abc";
    }

    function two(){
        $var2 = $var1;
        echo $var2; //This needs to output 'abc' for me.
    }
}

Unfortunately, it is not working. Can somebody help me please.

Marc
  • 19,394
  • 6
  • 47
  • 51
  • 1
    Does this answer your question? [Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?](https://stackoverflow.com/questions/16959576/reference-what-is-variable-scope-which-variables-are-accessible-from-where-and) – gre_gor May 26 '20 at 05:32
  • Yes I understand the scopes, but is there a anyway i can access that variable defined in another function? – shashi kumar May 26 '20 at 05:37
  • 2
    "*Yes I understand the scopes*" Obviously not. – gre_gor May 26 '20 at 05:40
  • I would suggest you also read up on [class properties](https://www.php.net/manual/en/language.oop5.properties.php) – M. Eriksson May 26 '20 at 06:00

1 Answers1

0

There are many ways to achieve this, one of the ways is mentioned below, if you're learning OOP then I'd suggest watching mmtuts videos which are quite informative.

<?php 

class Home{

    public $var1 = 'xyz';

    function one($x){ // or public function ... 

        $this->var1 = $x;
    }

    function two(){ // or public function ...

        $var2 = $this->var1;
        echo "var2: {$var2}"; //This needs to output 'abc' for me.
    }

}

$xyz = new Home(); // instantiate the class
$xyz->one('abc'); // call the function, pass the variable 
$xyz->two();    // get the value
sauhardnc
  • 1,961
  • 2
  • 6
  • 16