如何在PHP中从对象本身重新为对象变量赋值


How can I re-assign a value to an object variable from the object itself in PHP?

我正在创建一个具有字符串验证方法的类。我不能像这样重新为对象引用赋值:

class clearText
{
    private $text;
    function __construct($input)
    {
        $this->text = $input;
    }
    public function clearUp()
    {
        // …
        // functions to sanitize the string in $this->text
        // …
        $this = $this->text;
    }
}
$content = new clearText($_POST['content']);
$content->clearUp();

作为上面的例子输出:

致命错误:无法在''clearText.php13行重新分配$this

当我调用clearUp()时,我不再需要该对象,所以每次调用方法时,我都希望避免像这里这样指定此赋值

$content = new clearText($_POST['content']);
$content->clearUp();
$content = $content->text;

在方法中有什么方法可以做到这一点吗?


一个可能的答案

有人建议返回该值,这样我就可以在执行该方法的同一语句中将其重新分配给对象变量。答案已经被删除了,但它符合我的需要。

方法定义:

public function clearUp()
{
    // …
    // functions to sanitize the string in $this->text
    // …
    return $this->text;
}

实例化时:

$content = new clearText($_POST['content']);
$content = $content->clearUp();

不调用clearUp()方法,而是调用unset()。不过,请先将字符串分配给另一个变量。然而,这也将确保clearText对象使用的任何内存都被释放:

$content = new clearText($_POST['content']);
$content = $content->text;

否。$this实际上是您正在处理的类的实例。您永远不能将其设置为任何其他值。如果你愿意的话,这是一个"神奇"的关键词。

就像你不能把单词private设置为其他意思一样。

但是,您可以通过删除$content来销毁您的实例。