Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to explain 'this' keyword in a best and simple way?

Tags:

oop

php

this

I am using 'this' keyword for a long time. But when someone asks me to explain it, I am confused that how to explain it. I know that I can use this in a method of class to access any variable and method of the same class.

    class MyClass{

      function MyMethod1(){
        echo "Hello World";
      }

      function MyMethod2(){
        $this->MyMethod1();
      }

    }

Is it a object of a class that we don't need to initialise and can be used only within the class or anything else. How to explain?

Thanks

like image 823
Naveed Avatar asked Jan 19 '10 14:01

Naveed


People also ask

What is this keyword in simple terms?

The this keyword refers to the current object in a method or constructor. The most common use of the this keyword is to eliminate the confusion between class attributes and parameters with the same name (because a class attribute is shadowed by a method or constructor parameter).

How does the this keyword work?

“This” keyword refers to an object that is executing the current piece of code. It references the object that is executing the current function. If the function being referenced is a regular function, “this” references the global object.


2 Answers

A class is a mold for an object: it specifies how the object looks like (variables) and what it can do (functions).

If you instanciate a class: you create an object. If you create the class, you can use "this" to refer to the object itsself. This is why you can't set the "this", because it's related to the object. It's a special, read-only variable.

like image 127
Pindatjuh Avatar answered Sep 21 '22 03:09

Pindatjuh


this references the current object instance of a class.

this is an implicitly parameter passed to the methods of a class: it is scoped to a method and allows access to all of the object's members.

like image 41
jldupont Avatar answered Sep 19 '22 03:09

jldupont