How to daisy chain php classes [closed]

2019-09-21 18:14发布

问题:

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
  }
}