0

I have a php class and variable as follows:

class Test(){
function fun(){
 $a= 0;
 $b = 5;
 $sum = $b+c;
 return sum;
}
}

I can access the $sum from outside as follows:

$obj = new Test();
echo $obj->fun();

How can I access the value of $b from outside class?

Santhucool
  • 1,656
  • 2
  • 36
  • 92
  • possible duplicate of [Accessing variables and methods outside of class definitions](http://stackoverflow.com/questions/1415577/accessing-variables-and-methods-outside-of-class-definitions) – Sujay Sep 16 '15 at 06:49

2 Answers2

1

For this scenario you can use Object properties,

Define a public variable inside your class,

class Test(){

    public $b;

    function fun(){
        $a= 0;
        $this->b = 5;
        $sum = $this->b+c;
        return $sum;
    }
}

$obj = new Test();
$b = $obj->b; // here null
echo $obj->fun();
$b = $obj->b; // here 5
viral
  • 3,724
  • 1
  • 18
  • 32
1

You need to make $b as a public datamember to be able to access it from outside

class Test() {
    public $b = 5;

    public function fun(){
        $a= 0;
        $sum = $this->b + c;

        return sum;
    }
}

Now you have access to $b by doing this

$obj = new Test();
echo $obj->b;
Mike Vranckx
  • 5,557
  • 3
  • 25
  • 28