What does $this mean in PHP? [duplicate]

怎甘沉沦 提交于 2019-11-26 21:34:54

问题


Possible Duplicate:
PHP: self vs this

Hello, Could you help me understanding the meaning of the PHP variable name $this?

Thank you for your help.


回答1:


$this refers to the class you are in.

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.




回答2:


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?

Basically, $this refers to the current object.




回答3:


$this is a protected variable that's used within a object, $this allows you to access a class file internally.

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.

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

Some links for you to get started:

  • http://php.net/manual/en/language.variables.scope.php
  • http://php.net/manual/en/language.oop5.static.php
  • How to explain 'this' keyword in a best and simple way?
  • When to use self over $this?


来源:https://stackoverflow.com/questions/4124982/what-does-this-mean-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!