How to daisy chain php classes [closed]

≯℡__Kan透↙ 提交于 2019-12-13 08:29:03

问题


I want to do this.

$ppl->tech->ceo->apple();

How would I make that work?


回答1:


For example:

class ppl {
  public $tech;

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

class tech {
  public $ceo;

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

class ceo {
  public function __construct(){

  }

  public function apple(){
    echo 'Hello.. I\'m apple.';
  }
}



回答2:


Daisy chaining can be achieved by returning a pointer to the object. It is often used to connect methods together like:

$db = new db();
$myquery = $db->Select('mytable')->Where('a > 1')->Execute();

Daisy chaining is not about connecting properties with new classes;

Example:

class db 
{
  public function Select( $table )
  {
    // do stuff
    return $this;
  }

  public function Where( $Criterium )
  {
    // do stuff
    return $this;
  }

  public function Execute()
  {
    // do real work, return a result
  }
}


来源:https://stackoverflow.com/questions/12853573/how-to-daisy-chain-php-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!