$this是什么意思 [英] What is the meaning of $this
问题描述
我看到一些脚本在具有 OOP 的 PHP 脚本中包含 $this
,我从来不知道它的含义......就像
I've seen some scripts contain $this
in a PHP script that has OOP, I never knew the meaning of it... like
$this->refresh();
也许可以向我解释一下 $this
指的是什么...?
Perhaps explain to me what $this
refers to be...?
但我知道你不能像 $this_is_a_variable
那样将它用作动态变量,但为什么不能将它用作动态变量呢?
But I do know that you cannot use it as a dynamic variable like $this_is_a_variable
but why can't use it as a dynamic variable?
推荐答案
$this
是对当前对象的引用.
$this
is a reference to the current object.
只能在类方法中使用.
来自手册:
伪变量 $this 在对象上下文中调用方法时可用.$this 是对调用对象的引用(通常是该方法所属的对象,但也可能是另一个对象,如果该方法是从辅助对象的上下文中静态调用的).
The pseudo-variable $this is available when a method is called from within an object context. $this is a reference to the calling object (usually the object to which the method belongs, but possibly another object, if the method is called statically from the context of a secondary object).
一个简单的现实世界示例:
a simple real world example:
class Classname
{
private $message = "The big brown fox... jumped....";
function setMessage($givenMessage) {
$this->message = $givenMessage;
}
function getMessage() {
return $this->message; // Will output whatever value
// the object's message variable was set to
}
}
$my_object = new Classname(); // this is a valid object
echo $my_object->getMessage(); // Will output "The big brown fox... jumped...."
$my_object->setMessage("Hello World!");
echo $my_object->getMessage(); // Will output "Hello world"
$this
在静态上下文中调用方法时不可用:
$this
is not available when you call a method in a static context:
Classname::showMessage(); // Will throw an error:
// `$this` used while not in object context
这篇关于$this是什么意思的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!