描述
我实现了一个代表各种策略的Strategy
个类.每种策略在创建时都接受一个函数作为参数.该函数随后被绑定到策略,从而允许在匿名函数中使用$this.下面是一个例子:
$a = new Strategy(function () {
$this->getName(); // Strategy 1. $this refers to $a within this function.
});
在Strategy
类的构造函数中:
public function __construct(Closure $strategy)
{
self::initCounter();
$this->strategy = $strategy(...)->bindTo($this);
$this->name = 'Strategy ' . self::$strategyCounter->getNextStrategyNumber();
}
initCounter
方法初始化计数器,这是一个简单私有静态字段,对象为StrategyCounter
类,只有几个策略和方法来获取下一个数字-getNextNumber()
并递减数字-decrementStrategyCounter()
操作原理很简单:
在创建新的Strategy时,它会收到默认名称:"Strategy X",其中X是下一个策略的编号.例如:
$a = new Strategy(function () {}); // Name = Strategy 1
$b = new Strategy(function () {}); // Name = Strategy 2
// and so on.
问题在哪里,我想实现的目标是什么?
我还希望策略的名称不会被阻止,即,如果对象被删除/取消设置,则计数器应该递减,以便新策略可以使用该名称,如下所示:
$a = new Strategy(function () {}); // Name = Strategy 1
$b = new Strategy(function () {}); // Name = Strategy 2
unset($b); // $b is unset => Counter decremented => Default name for next Strategy should be with number 2.
$c = new Strategy(function () {}); // Name = Strategy 2
不幸的是,我无法使用__destruct()
来实现这一点,因为对Strategy
的引用在Closure
中
我所try 的
我想也许我应该首先删除析构函数中的闭包,但这并不起作用:
public function __destruct()
{
unset($this->strategy);
self::$strategyCounter->decrementStrategyCounter();
}
这是因为根本没有调用析构函数. 我是这样理解的:
$a = new Strategy(function () {}); // Name = Strategy 1
$b = new Strategy(function () {}); // Name = Strategy 2
unset($b); // $b isn't unset, because Strategy still exists, because was bind to Closure within that Strategy, and since this is the case, no destuctor is called.
$c = new Strategy(function () {}); // Name = Strategy 3 Blehh ;C
// The script ends, all Strategies are removed one by one.