对象陷入无限循环


Object gets stuck in an infinite loop

我试图处理OOP的一个简单想法,但我已经有一段时间没有使用这样的东西了。

class UserAPI
{
    protected $Email;
    protected $APIKey;
    public function setEmail($e)
    {
        $this->Email = $e;
        return (new UserAPI)->setEmail($this->Email);
    }
    public function setKey($k)
    {
        $k = hash('SHA256',$k);
        $this->APIKey = $k;
        echo 'Key Wrote';
        return (new UserAPI)->setEmail($this->Email)->setKey($this->APIKey);
    }
    public function getVals(){ echo 'Vals wrote;'; return array('key' => $this->APIKey, 'email' => $this->Email); }
}
print_r((new UserAPI)->setEmail('Example')
        ->setKey('Password')
        ->getVals());

正如你可能收集到的,(new UserAPI)->setEmail('...')将陷入无限循环——最终,setKey()也会陷入无限循环;我已经被这个问题困扰了很长时间,不知道如何返回新对象以继续使用。

任何帮助都是完美的。

在类中使用$this->来引用对象本身,并使用new UserAPI()创建一个新对象。

class UserAPI
{
    protected $Email;
    protected $APIKey;
    public function setEmail($e)
    {
        $this->Email = $e;
        return $this;
    }
    public function setKey($k)
    {
        $k = hash('SHA256',$k);
        $this->APIKey = $k;
        echo 'Key Wrote';
        return $this;
    }
    public function getVals(){ 
        echo 'Vals wrote;'; 
        return array('key' => $this->APIKey, 'email' => $this->Email); 
    }
}
// this...
$u = new UserAPI();       // create object
$u->setEmail('Example');  // set e-mail
$u->setKey('Password');   // set password
print_r($u->getVals());   // get values
// ...is equivalent to this...
$u = new UserAPI();           // create object
print_r(
    $u->setEmail('Example')   // set mail
    ->setKey('Password')      // set password
    ->getVals());             // get values
// ...but only where the class methods return the object
// (ie. not for getValues())

只需返回$this,就可以将类传播到另一个派生调用。

但是,