PHP 中的 $this 变量是什么意思?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1523479/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 02:56:14  来源:igfitidea点击:

What does the variable $this mean in PHP?

phpclassoopthis

提问by waiwai933

I see the variable $thisin PHP all the time and I have no idea what it's used for. I've never personally used it.

我一直$this在 PHP 中看到该变量,但我不知道它的用途。我从来没有亲自使用过。

Can someone tell me how the variable $thisworks in PHP?

有人能告诉我这个变量$this在 PHP 中是如何工作的吗?

回答by meder omuraliev

It's a reference to the current object, it's most commonly used in object oriented code.

它是对当前对象的引用,最常用于面向对象的代码中。

Example:

例子:

<?php
class Person {
    public $name;

    function __construct( $name ) {
        $this->name = $name;
    }
};

$Hyman = new Person('Hyman');
echo $Hyman->name;

This stores the 'Hyman' string as a property of the object created.

这将“Hyman”字符串存储为所创建对象的属性。

回答by Eric Leschinski

The best way to learn about the $thisvariable in PHP is to try it against the interpreter in various contexts:

了解$thisPHP 中变量的最好方法是在各种上下文中对解释器进行尝试:

print isset($this);              //true,   $this exists
print gettype($this);            //Object, $this is an object 
print is_array($this);           //false,  $this isn't an array
print get_object_vars($this);    //true,   $this's variables are an array
print is_object($this);          //true,   $this is still an object
print get_class($this);          //YourProject\YourFile\YourClass
print get_parent_class($this);   //YourBundle\YourStuff\YourParentClass
print gettype($this->container); //object
print_r($this);                  //delicious data dump of $this
print $this->yourvariable        //access $this variable with ->

So the $thispseudo-variable has the Current Object's method's and properties. Such a thing is useful because it lets you access all member variables and member methods inside the class. For example:

所以$this伪变量具有当前对象的方法和属性。这样的东西很有用,因为它允许您访问类中的所有成员变量和成员方法。例如:

Class Dog{
    public $my_member_variable;                             //member variable

    function normal_method_inside_Dog() {                   //member method

        //Assign data to member variable from inside the member method
        $this->my_member_variable = "whatever";

        //Get data from member variable from inside the member method.
        print $this->my_member_variable;
    }
}

$thisis reference to a PHP Objectthat was created by the interpreter for you, that contains an array of variables.

$this是对Object解释器为您创建的 PHP 的引用,其中包含变量数组。

If you call $thisinside a normal method in a normal class, $thisreturns the Object (the class) to which that method belongs.

如果$this在普通类中调用普通方法,则$this返回该方法所属的对象(类)。

It's possible for $thisto be undefined if the context has no parent Object.

$this如果上下文没有父对象,则可能未定义。

php.net has a big page talking about PHP object oriented programming and how $thisbehaves depending on context. https://www.php.net/manual/en/language.oop5.basic.php

php.net 有一个很大的页面讨论 PHP 面向对象的编程以及如何$this根据上下文进行操作。 https://www.php.net/manual/en/language.oop5.basic.php

回答by loyola

I know its old question, anyway another exact explanation about $this. $thisis mainly used to refer properties of a class.

我知道它的老问题,无论如何另一个关于$this 的确切解释。$this主要用于引用类的属性。

Example:

例子:

Class A
{
   public $myname;    //this is a member variable of this class

function callme() {
    $myname = 'function variable';
    $this->myname = 'Member variable';
    echo $myname;                  //prints function variable
    echo $this->myname;              //prints member variable
   }
}

output:

输出:

function variable

member variable

回答by snicker

It is the way to reference an instance of a class from within itself, the same as many other object oriented languages.

它是从自身内部引用类实例的方式,与许多其他面向对象语言相同。

From the PHP docs:

来自PHP 文档

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).

当从对象上下文中调用方法时,伪变量 $this 可用。$this 是对调用对象的引用(通常是该方法所属的对象,但也可能是另一个对象,如果该方法是从辅助对象的上下文中静态调用的)。

回答by user6485832

Lets see what happens if we won't use $this and try to have instance variables and constructor arguments with the same name with the following code snippet

让我们看看如果我们不使用 $this 并尝试使用以下代码片段使用同名的实例变量和构造函数参数会发生什么

<?php

class Student {
    public $name;

    function __construct( $name ) {
        $name = $name;
    }
};

$tom = new Student('Tom');
echo $tom->name;

?>

It echos nothing but

它只回响

<?php

class Student {
    public $name;

    function __construct( $name ) {
        $this->name = $name; // Using 'this' to access the student's name
    }
};

$tom = new Student('Tom');
echo $tom->name;

?>

this echoes 'Tom'

这与“汤姆”相呼应

回答by cp3

when you create a class you have (in many cases) instance variables and methods (aka. functions). $this accesses those instance variables so that your functions can take those variables and do what they need to do whatever you want with them.

当您创建一个类时,您(在许多情况下)拥有实例变量和方法(又名函数)。$this 访问这些实例变量,以便您的函数可以使用这些变量并执行它们需要的任何操作。

another version of meder's example:

另一个版本的 meder 示例:

class Person {

    protected $name;  //can't be accessed from outside the class

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}
// this line creates an instance of the class Person setting "Hyman" as $name.  
// __construct() gets executed when you declare it within the class.
$Hyman = new Person("Hyman"); 

echo $Hyman->getName();

Output:

Hyman

回答by Seyedan

$thisis 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).

$this对调用对象的引用(通常是该方法所属的对象,但也可能是另一个对象,如果该方法是从辅助对象的上下文中静态调用的)。

回答by homi

$this is a special variable and it refers to the same object ie. itself.

$this 是一个特殊的变量,它指的是同一个对象,即。本身。

it actually refer instance of current class

它实际上是指当前类的实例

here is an example which will clear the above statement

这是一个示例,它将清除上述语句

<?php
 class Books {
  /* Member variables */
  var $price;
  var $title;

  /* Member functions */
  function setPrice($par){
     $this->price = $par;
  }

  function getPrice(){
     echo $this->price ."<br/>";
  }

  function setTitle($par){
     $this->title = $par;
  }

  function getTitle(){
     echo $this->title ." <br/>";
  }
}
?> 

回答by Marc W

It refers to the instance of the current class, as medersaid.

正如meder所说,它指的是当前类的实例。

See the PHP Docs. It's explained under the first example.

请参阅PHP 文档。它在第一个示例下进行了解释。