我和你有同样的问题,在某些时候我想让对象自己删除,但在 php 中是不可能的,所以这是一个可能对你有帮助的解决方法。
您可以设置一个私有标志并在每个需要该对象的方法中检查该标志是否仍然存在,例如:
<?php
class Bar {
// internal flag
private $_removed = false;
public function remove() {
// ... some code
$this->_removed = true;
}
private function checkExceptionRemoved() {
if ($this->_removed) throw new RuntimeException("The object has been removed");
}
public function show() {
$this->checkExceptionRemoved();
// ... some code
}
}
?>
其他方法可能是重载 _call 方法并在调用该方法之前查看标志,这也可能需要使用一些前缀重命名方法,例如“pub”,以便在 __call 方法中进行调用.这是一个例子:
class Foo {
private $_value;
private $_valid = true;
public function IsValid() {
return $this->_valid;
}
private function IsValidException() {
if (!$this->IsValid()) throw new RuntimeException("The object has been removed");
}
public function __construct($value) {
$this->_value = $value;
}
public function __call($name, $arguments) {
if (!$this->IsValid()) throw new RuntimeException("The object has been removed");
if (!method_exists($this, "_$name")) throw new Exception("Invalid call, method '$name' does not exists");
return call_user_func_array(array($this, "_$name"), $arguments);
}
protected function _show() {
echo print_r($this->_value, true)."\n";
}
protected function _remove() {
$this->_valid = false;
}
}
$foo = new Foo("Foo Object");
$foo->show();
$foo->remove();
$foo->show(); // Exception !!!
?>
恕我直言,对象无法将自己从内存中删除是一个真正的问题,但这是 PHP 设计的一部分,它不是 C++。作为左派的想法,对于这个和其他事情,您可以在其他语言/库中传递应用程序的逻辑,这些语言/库是用 C++/C# 等其他语言开发的,并使用 PHP 来使用该逻辑,例如“HTML/CSS/JS/PlainText PHP C# Cli 数据库/文件/存储"