$this 在 PHP 中是什么意思?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4124982/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What does $this mean in PHP?
提问by Xela C
Possible Duplicate:
PHP: self vs this
可能的重复:
PHP:self vs this
Hello,
Could you help me understanding the meaning of the PHP variable name $this
?
您好,您能帮我理解 PHP 变量名的含义$this
吗?
Thank you for your help.
感谢您的帮助。
回答by jodm
$this
refers to the class you are in.
$this
指的是你所在的班级。
For example
例如
Class Car {
function test() {
return "Test function called";
}
function another_test() {
echo $this->test(); // This will echo "Test function called";
}
}
Hope this helps.
希望这可以帮助。
回答by Michael Paulukonis
You might want to have a look at the answers in In PHP5, what is the difference between using self and $this? When is each appropriate?
您可能想看看在 PHP5中的答案,使用 self 和 $this 有什么区别?什么时候合适?
Basically, $this
refers to the current object.
基本上,$this
指的是当前对象。
回答by RobertPitt
$this
is a protected variable that's used within a object, $this
allows you to access a class file internally.
$this
是在对象中使用的受保护变量,$this
允许您在内部访问类文件。
Example
例子
Class Xela
{
var age; //Point 1
public function __construct($age)
{
$this->setAge($age); //setAge is called by $this internally so the private method will be run
}
private function setAge($age)
{
$this->age = $age; //$this->age is the variable set at point 1
}
}
Its basically a variable scope issue, $this
is only allowed within a object that has been initiated and refers to that object and its parents only, you can run private methods and set private variables where as out side the scope you cannot.
它基本上是一个变量范围问题,$this
仅允许在已启动的对象内并仅引用该对象及其父对象,您可以运行私有方法并设置私有变量,而在范围之外则不能。
also the self
keyword is very similar apart from it refers to static methods within class, static basically means that you cant use $this
as its not an object yet, you must use self::setAge();
and if that setAge
method is declared static then you cannot call it from an instant of that object / object
还self
关键字是非常相似的除了它是指内静态方法类,静态基本上意味着你不能使用$this
它的不是一个对象是,你必须使用self::setAge();
,如果该setAge
方法被声明为static,那么你不能从那个瞬间叫它目的 /object
Some links for you to get started:
一些链接供您入门: