Php 对象陷入无限循环中

Php 对象陷入无限循环中,php,oop,Php,Oop,我正试图接近OOP的一个简单概念,但我已经有一段时间没有使用类似的东西了 class UserAPI { protected $Email; protected $APIKey; public function setEmail($e) { $this->Email = $e; return (new UserAPI)->setEmail($this->Email); } public functi

我正试图接近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());
正如您可能收集到的那样,
(新用户API)->setEmail(“…”)
将陷入一个无限循环中,因此,
setKey()
;我已经在这个问题上纠缠了很久,不知道如何返回新对象以继续使用


任何帮助都是完美的。

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

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


但是,

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

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


但是,

setEmail是递归的。为什么
UserAPI
在调用
setEmail()
时创建一个
UserAPI
的新实例?为什么不直接返回
$this
?其目的是能够像magento一样,通过返回当前对象属性以供进一步添加,允许用户在对象更改时使用该对象。return(new UserAPI)->setEmail($this->Email);在无限递归中!对于它,您应该具有终止条件或返回$this,正如Mark BakersetEmail所建议的,这是递归的。为什么
UserAPI
在调用
setEmail()
时创建一个
UserAPI
的新实例?为什么不直接返回
$this
?这个想法是能够像magento一样,通过返回当前对象属性以供进一步添加,允许用户在对象更改时使用该对象。return(new UserAPI)->setEmail($this->Email);在无限递归中!你应该有一个终止条件,或者按照马克·贝克尔的建议返还$this,这太完美了!我知道必须运行两次方法有点狡猾,这是可行的。非常感谢当我感谢你的感激时,我会记下的。太好了!我知道必须运行两次方法有点狡猾,这是可行的。非常感谢当我感谢你的感激时,我会记下的。嗯。
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())