【问题标题】:What does $this mean in PHP? [duplicate]$this 在 PHP 中是什么意思? [复制]
【发布时间】:2011-05-06 17:10:16
【问题描述】:

可能重复:
PHP: self vs this

你好, 你能帮我理解PHP变量名$this的含义吗?

感谢您的帮助。

【问题讨论】:

  • 可能重复:stackoverflow.com/questions/151969/php-self-vs-this。另外,请不要在提问时太可爱。 ;)
  • 恭喜你在12岁扩展知识!但是由于这与问题无关,您可以编辑问题以将其删除吗?
  • 看起来 Stack Overflow 上的人不知道“我今年 12 岁,这是什么”指的是什么。
  • 这是怎么个骗子,他没有比较self$this的用法,特别想知道什么 $this是什么意思。

标签: php oop this keyword


【解决方案1】:

$this 指的是你所在的班级。

例如

Class Car {

    function test() {
        return "Test function called";
    }

    function another_test() {
        echo $this->test(); // This will echo "Test function called";
    }
}

希望这会有所帮助。

【讨论】:

  • 这是一种引用自身的方式...或调用方法或从自身读取变量。
  • 其实self指的是你当前所在的类,$this指的是你所在类的当前对象实例。
  • 它不会 echo "Test functioned called" 因为您访问的是 test 成员变量(不存在)而不是方法 test()。您需要将其更改为 echo $this->test()...
  • 它不是真正的,而是object——一个类的instance
  • 实际上它是该类的一个实例,其中self 将静态引用该类,而__CLASS__ 将类名作为字符串引用:-)
【解决方案2】:

您可能想看看In PHP5, what is the difference between using self and $this? When is each appropriate?中的答案

基本上,$this 指的是当前对象。

【讨论】:

    【解决方案3】:

    $this 是在对象中使用的受保护变量,$this 允许您在内部访问类文件。

    例子

    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
       }
    }
    

    它基本上是一个变量范围问题,$this 仅允许在已启动的对象中使用,并且仅引用该对象及其父对象,您可以运行私有方法并设置私有变量,因为您不能在范围之外.

    self 关键字也很相似,除了它指的是 class 中的静态方法,static 基本上意味着你不能使用$this,因为它还不是一个对象,你必须使用@ 987654331@ 并且如果 setAge 方法被声明为静态,那么您不能从该对象的瞬间调用它/object

    一些链接供您开始使用:

    【讨论】:

    • 虽然我理解您是在向 OOP 新手解释,但请不要将对象称为类。 $this 用于引用对象属性和方法,而 self:: 用于引用类属性和方法。我认为解释两者之间的区别很重要。
    猜你喜欢
    • 2015-05-01
    • 2017-07-09
    • 1970-01-01
    • 2011-05-10
    • 2012-05-04
    • 2015-06-27
    • 1970-01-01
    • 1970-01-01
    • 2013-06-15
    相关资源
    最近更新 更多