-2

So i have a php class and i'm having a small snarl up. imagine a class as one shown below

<?php
class Foo
{
   public function __construct()
  {
     $this->bar1();
  }
  public function bar1()
  {
    $myvar = 'Booya!';

   return 'Something different';
  }
  public function bar2()
  {
    //get value of $myvar from bar1()
  }
}
$new_foo = new Foo();
$new_foo->bar2();
?>

Question is, how do I access the variable $myvar from bar1() keeping in mind that bar1() returns something different.

John Kariuki
  • 4,966
  • 5
  • 21
  • 30

4 Answers4

2

You would do something like this... Everything has been explained through comments next to the code.

<?php
class Foo
{
    private $myvar; //<---- Declare the variable !
    public function __construct()
    {
        $this->bar1();
    }
    public function bar1()
    {
        $this->myvar = 'Booya!'; //<---- Use this $this keyword

        //return 'Something different';//<--- Comment it.. Its not required !
    }
    public function bar2()
    {
        return $this->myvar; //<----- You need to add the return keyword
    }
}
$new_foo = new Foo();
echo $new_foo->bar2(); //"prints" Booya!
Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126
2
<?php
class Foo
{
  var $myvar;
  public function __construct()
  {
     $this->bar1();
  }
  public function bar1()
  {
    $this->myvar = 'Booya!';

   return 'Something different';
  }
  public function bar2()
  {
    //get value of $myvar from bar1()
    echo $this->myvar;
  }
}
$new_foo = new Foo();
$new_foo->bar2();
?>

You should set it as a class variable first, then access it using $this

Adam
  • 1,957
  • 3
  • 27
  • 56
2

You cannot do that directly, only you can do without altering bar1() return value is create a class variable for saving the value of this data In class definition add

private $saved_data;

In bar1():

$myvar = 'Booya!';
$this->saved_data = $myvar;

And in bar2()

$myvar_from_bar1 = $this->saved_data
Olvathar
  • 551
  • 3
  • 10
0

Use class variables like:

$this->myvar = 'Booya!';

Now the variable myvar will be store in the class and can be requested or altered in other methods.

Pakspul
  • 648
  • 5
  • 17