0

如果我有以下 PHP 类示例设置...

class foo {
  public $x = 2;

  public function getX() {
    return $this->x;
  }

  public function setX($val) {
    $this->x = $val - $this->x;
    return $this;
  } 
}

$X = (new foo)->setX(20)->getX();

我怎么需要 ->getX(); 在对象启动过程结束时获得 18 的部分?为什么我根本无法隐藏公共 getX() 函数并编写...

$X = (new foo)->setX(20);
echo $X; // and show 18 without errors.

相反,它会抛出一个错误并说......

Catchable fatal error: Object of class foo could not be converted to string in C:\...

是不是$this->x 指大众$x = 2?我想我有点困惑为什么我们依赖 Public function getX()。提前感谢您的帮助理解!

4

2 回答 2

2

foo因为你在做的时候返回了一个类的实例return $this;。如果您希望它像上面那样工作,那么您需要返回$x如下所示:

  public function setX($val) {
    $this->x = $val - $this->x;
    return $this->x;
  } 
于 2012-11-14T14:45:27.867 回答
2

echo $X尝试输出对象。但是您的对象没有魔法方法 __toString(),因此 PHP 无法确切知道在字符串上下文中使用对象时要输出什么。

例如,如果您将其添加到您的对象定义中:

public function __toString() {
   return $this->getX();
}

18当你这样做时,你会“正确地”得到echo $X

于 2012-11-14T14:46:04.153 回答