如何启动由 trait 定义的构造函数和析构函数以及类的构造函数和析构函数。例如,
trait Audit
{
public function __construct()
{
parent::__construct(); // Doesn't work...
$this->_name = __CLASS__;
$this->AuditAction('Started');
}
public function __destruct()
{
parent::__destruct(); // Doesn't work...
$this->AuditAction('Ended');
echo $this->_log;
}
public function AuditAction($n)
{
$this->_log .= $this->GetCurrentTimeStamp() . ' ' . $this->_name . ": $n" . PHP_EOL;
}
private function GetCurrentTimeStamp()
{
return (new DateTime())->format('[Y-m-d H:i:s]');
}
private $_name, $_log = '';
}
class C
{
use Audit;
public function __construct()
{
}
public function __destruct()
{
}
}
$c = new C();
我应该得到几行文本,但我没有得到,因为 C 类的构造函数是显式调用的。有没有办法做到这一点?