首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >变量$this在PHP中是什么意思?

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

Stack Overflow用户
提问于 2009-10-06 03:45:08
回答 6查看 238.1K关注 0票数 119

我在PHP中经常看到变量$this,我不知道它是用来做什么的。我从来没有亲自使用过它。

谁能告诉我在PHP中变量$this是如何工作的?

EN

回答 6

Stack Overflow用户

发布于 2013-12-12 02:23:59

学习PHP语言中$this变量的最好方法是在不同的上下文中尝试使用解释器:

代码语言:javascript
复制
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 ->

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

代码语言:javascript
复制
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;
    }
}

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

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

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

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

票数 44
EN

Stack Overflow用户

发布于 2016-06-19 22:59:00

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

代码语言:javascript
复制
<?php

class Student {
    public $name;

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

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

?>

它回响的只有

代码语言:javascript
复制
<?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;

?>

这是对“Tom”的回应。

票数 7
EN

Stack Overflow用户

发布于 2009-10-06 14:47:10

当你创建一个类时,你有(在许多情况下)实例变量和方法(也称为。函数)。$this访问这些实例变量,以便您的函数可以获取这些变量,并执行您想要对它们执行的任何操作。

meder例子的另一个版本:

代码语言:javascript
复制
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 "Jack" as $name.  
// __construct() gets executed when you declare it within the class.
$jack = new Person("Jack"); 

echo $jack->getName();

Output:

Jack
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1523479

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档