变量$这在PHP中意味着什么?

wai*_*933 98 php oop class this

我一直$this在PHP中看到变量,我不知道它用于什么.我从来没有亲自使用它,搜索引擎忽略了这一点$this,我最终搜索了"this"这个词.

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

med*_*iev 122

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

例:

<?php
class Person {
    public $name;

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

$jack = new Person('Jack');
echo $jack->name;
Run Code Online (Sandbox Code Playgroud)

这将'Jack'字符串存储为创建的对象的属性.


Eri*_*ski 37

$this在php中了解变量的最佳方法是询问PHP是什么.不要问我们,请问编译器:

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 ->
Run Code Online (Sandbox Code Playgroud)


loy*_*ola 14

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

例:

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
   }
}
Run Code Online (Sandbox Code Playgroud)

输出:

function variable

member variable
Run Code Online (Sandbox Code Playgroud)


sni*_*ker 8

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

PHP文档:

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


小智 7

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

<?php

class Student {
    public $name;

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

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

?>
Run Code Online (Sandbox Code Playgroud)

它没有回音

<?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;

?>
Run Code Online (Sandbox Code Playgroud)

这与'汤姆'相呼应

  • 你的代码片段是完全一样的,还是我错过了什么? (2认同)