我在外部类上有一个公共方法
public function nextStep()
{
return $this->step++;
}
对象$this->step
是公开的
public $step;
我在构造方法
上分配它的值public function __construct($step)
{
$this->step = $step;
}
我从另一个定义
的类中调用此方法public $step = 0;
然后我做
$call = new StasisFlash\StasisFlash($this->step);
$nextStep = $call->nextStep();
那应该返回1而是返回0.我试图直接打印$call->nextStep()
并返回1但是如果我尝试将值赋给变量或对象它返回0,即使我同时打印两个
感谢任何帮助
答案 0 :(得分:1)
这是因为$i++
运算符在>>递增之前返回值。
$i = 0;
echo $i++;
输出:0
++$i
运算符会在之后返回$i
,然后递增。
$i = 0;
echo ++$i;
输出:1
为了使您的代码更清晰,最好添加额外的行。它还消除了您尝试做的任何不确定性。
public function nextStep()
{
$this->step++;
return $this->step;
}
答案 1 :(得分:1)
您使用$this
的方式无效。此后缀仅在类范围内可用。
看一下下面的例子。
class Duck
{
// Set the default leg amount
public $legs = 0;
// This is called when creating a 'new Duck()' object
public function __construct($legs = false)
{
// If a different amount of legs is set...
if (false !== $legs) {
$this->legs = $legs;
}
}
}
$duckOne = new Duck(5);
echo "The duck has ".$duckOne->legs." legs.";
// Returns: The duck has 5 legs.
$duckTwo = new Duck();
echo "The duck has ".$duckTwo->legs." legs.";
// Returns: The duck has 0 legs.
您基本上要做的是:
echo $hello;
$hello = "Good day!";
您正在使用$this
,但它不存在。
Class Example
{
public function method()
{
// You can only use $this here
}
}
// You cannot use $this here because it is not defined
$example = new Example();