I am method chaining in PHP, something like this:
$c = new someClass();
$c->blackMethod()->colourMethod();
$c->whiteMethod()->colourMethod();
Is there any way the colourMethod() can know if it was called after the blackMethod() or whiteMethod()? In other words, is there a way of getting the name of the previously called method in a chain of methods?
Something like this:
$c->blackMethod()->colourMethod();
//output: "The colour is black";
$c->whiteMethod()->colourMethod();
//output: "The colour is white";
I understand that chaining is only shorthand for calling multiple methods from the same class, but I was hoping there is a way to link the chains together somehow.
I have tried debug_backtrace() and
$e = new Exception();
$trace = $e->getTrace();
but they only give class names or the name of the method that called the colourMethod (which is $c), not the method that was called before it.
答案 0 :(得分:2)
Just set a property on the object:
<?php
class ColorChanger
{
private $lastColor;
public function blackMethod() {
echo "blackMethod(); Last color: {$this->lastColor}\n";
$this->lastColor = 'black';
return $this;
}
public function whiteMethod() {
echo "whiteMethod(); Last color: {$this->lastColor}\n";
$this->lastColor = 'white';
return $this;
}
public function colourMethod() {
echo "colourMethod(): {$this->lastColor}\n";
$this->lastColor = null;
}
}
$c = new ColorChanger();
$c->blackMethod()->colourMethod();
$c->whiteMethod()->colourMethod();
$c->blackMethod()->whiteMethod()->colourMethod();
Example here.
If you need to get a history, use an array:
<?php
class ColorChanger
{
public $lastColors = [];
public function blackMethod() {
$colors = implode(', ', $this->lastColors);
echo "blackMethod(); Last colors: {$colors}\n";
$this->lastColors[] = 'black';
return $this;
}
public function whiteMethod() {
$colors = implode(', ', $this->lastColors);
echo "whiteMethod(); Last colors: {$colors}\n";
$this->lastColors[] = 'white';
return $this;
}
public function colourMethod() {
$colors = implode(', ', $this->lastColors);
$lastColor = $this->lastColors[count($this->lastColors)-1];
echo "colourMethod(): {$colors} (Last: $lastColor)\n";
$this->lastColors = [];
}
}
$c = new ColorChanger();
$c->blackMethod()->colourMethod();
$c->whiteMethod()->colourMethod();
$c->blackMethod()->whiteMethod()->blackMethod()->colourMethod();
答案 1 :(得分:0)
一种更好的,更通用的跟踪以前调用的方法的方法是使用私有或受保护的属性使用常量__FUNCTION__
或__METHOD__
跟踪实际方法。
例如:
class colorchanger
{
protected prevMethod;
public function black()
{
/*
your routine
for the black
method here
*/
$this->prevMethod =__FUNCTION__;
return $this;
}
public function white()
{
/*
your routine
for the white
method here
*/
$this->prevMethod =__FUNCTION__;
return $this;
}
public function colour()
{
return $this->prevMethod;
}
}
$c = new ColorChanger();
$c->black->colour();
$c->white()->colour();
$c->black()->white->colourMethod();//will return white instead of black