Douglas Roos Douglas Roos - 3 months ago 9
PHP Question

Cannot assign method to variable php

I have a public method on an external class

public function nextStep()
{
return $this->step++;
}


The object
$this->step
is public

public $step;


I assign the value of it on the construct method

public function __construct($step)
{
$this->step = $step;
}


I call this method from another class where i define

public $step = 0;


Then i do

$call = new StasisFlash\StasisFlash($this->step);
$nextStep = $call->nextStep();


That should return 1 but instead is returning 0. I've tried to print directly the
$call->nextStep()
and it returns 1 but if i try to assign the value to a variable or an object it returns 0, even if I print both at the same time

Appreciate any help

Answer

This is because the $i++ operator returns the value before it increments.

$i = 0;
echo $i++;

output: 0

Whereas the ++$i operator will return $i after it increments.

$i = 0;
echo ++$i;

output: 1


To make your code more legible it may be better to add an extra line. It also removes any uncertainty in what you're trying to do.

public function nextStep()
{
  $this->step++;
  return $this->step;
}
Comments