开发者

What is the purpose of "$this"? [duplicate]

开发者 https://www.devze.com 2023-03-12 17:39 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: What does $this mean in PHP?
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

What does $this mean in PHP?

What is the use of $this?

I'm getting the result correctly on both the following cases.

  1. Without $this

    class Car {
      function Beetle($colour) {
        return $colour;
      }
    }
    
    $car = new Car();
    
    echo $car->Beetle("Blue");
    
  2. W开发者_如何转开发ith $this

    class Car {
      function Beetle($colour) {
        $this->colour = $colour;
        return $colour;
      }
    }
    
    $car=new Car();
    
    echo $car->Beetle("Blue");
    

On both the cases, I'm getting the same result: "Blue."

I don't understand why and for what we are using $this.


$this refers to the instantiated object that was created with the new operator.

Your first code example just returns the argument ($colour) passed to it.

Your second example assigns the property to its object (with $this) and then returns the argument again.


As far as I understannd $this is used to access variables and methods in the class you are in, it is essentially an object of the class. In both your examples you are returning the input parameter anyway.

Without $this;

class Car{

  private $colour;

  function Beetle($colour) {
    return $this->colour;
  }
}

With $this;

class Car{

  private $colour;

  function Beetle($colour) {
    $this->colour = $colour;
    return $this->$colour;
  }
}

What i'm trying to show you here is that in the first example it will return null as the property colour hasn't been set by the function, wheras the second example it sets the property to the input variable and will return the value that is passed in.

In short, $this is how we access properties and methods that belong to the class.


Because you may have multiple instances (objects) of the same class.

class Car {
   var colour;
   var parkedNextTo;
   function setColout($colour)
   {
      $this->colour=$colour;
   }
   function park($nextTo)
   {
      $this->$nextTo=$nextTo;
   }
}

$beetle=new Car();
$beetle->setColour('blue');

$jeep=new Car();
$jeep->setColour('red');
$jeep->nextTo($beetle);
0

精彩评论

暂无评论...
验证码 换一张
取 消