在 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.php第13行重新分配$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();
I'm creating a class with string validating methods. I cannot re-assign a value to the object reference like this:
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();
as the above example outputs:
Fatal error: Cannot re-assign $this in \clearText.php on line 13
When I call clearUp()
, I don't need the object anymore, so I would like to avoid specifying this assignment like here, every time I call the method:
$content = new clearText($_POST['content']);
$content->clearUp();
$content = $content->text;
Is there any way to do this inside the method?
A possible answer
Somebody suggested returning the value, so I can re-assign it to the object variable in the same statement, that execute the method. The answer has since been deleted, but it works for what I need.
Method definiton:
public function clearUp()
{
// …
// functions to sanitize the string in $this->text
// …
return $this->text;
}
When instantiated:
$content = new clearText($_POST['content']);
$content = $content->clearUp();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不要调用
clearUp()
方法,而是调用unset()
。不过,之前将字符串分配给另一个变量。但是,这也将确保释放clearText
对象使用的所有内存:Instead of calling the
clearUp()
method, callunset()
. Assign the string to another variable before though. However, this will also ensure that any memory used by theclearText
object is released:不。
$this
是您正在处理的类的实际实例。您无法将其设置为任何其他值。如果你愿意的话,这是一个“神奇”的关键字。就像你不能将单词
private
设置为其他含义一样。不过,您可以通过删除
$content
来销毁您的实例。No.
$this
is the actually instance of the class that you're dealing with. You can't set it to any other value ever. It's a 'magic' keyword if you will.Much like how you can't set the word
private
to mean something else.You can destroy your instance by deleting
$content
however.