0

I need to access a variable in a loop outside the for a loop.

I have defined the variable outside the class function as a private variable like this.

private $counter;

Then inside the function, I have used it like this.

public function counter_loop(){
  for($i=0;$i<100;$i++){
  $this->counter++;
}
return $this->counter;
}

But getting an error saying $counter is undefined.

Mujahid Bhoraniya
  • 1,518
  • 10
  • 22
CodeCanyon
  • 929
  • 2
  • 11
  • 36
  • its in controller ? it working without error ?? – Hamelraj Mar 10 '20 at 05:50
  • Yes in the same controller. But it's quite confusing for me since not working – CodeCanyon Mar 10 '20 at 05:52
  • 1
    with your code i just checked , for me its return 100 ...... !? – Hamelraj Mar 10 '20 at 05:55
  • 2
    Since `$counter` isn't used in your pasted code, the error lies elsewhere. –  Mar 10 '20 at 05:57
  • are you trying from sub classes ? just read this https://stackoverflow.com/questions/1762135/accessing-private-variable-from-member-function-in-php – Hamelraj Mar 10 '20 at 06:13
  • It depends on how you're trying to print the $counter variable. `echo $object->counter_loop()` will print `100` (where `$object` is an instance of the class). Show how you're trying to access the variable in your code. – ash__939 Mar 10 '20 at 06:19
  • are you sure you are not just making a spelling mistake while using the variable name ? this happens you know... coz for me its also reverting 100 – Mohammed Samgan Khan Mar 10 '20 at 08:48

1 Answers1

0

$counter is undefined because there isn't an initial value. Try this:

private $counter = 0;
Buddy
  • 10,874
  • 5
  • 41
  • 58