PHP Interview questions


Total available count: 33
Subject - PHP Frameworks
Subsubject - PHP

What is the difference between self and $this?

In general terms, we can say that $this is used to reference the current object and as well as self is used to access the current class itself. In the below examples, we have a class called Slightbook and derived class called Bookslight. The Bookslight class overrides the whichClass() function – Below example shows where we use the $this pointer:

Example:

Bookslight { 
   public function whichClass() 
   { 
      echo "I am an Slightbook!.."; 
   } /* This method uses the $this keyword so calling object's type (Bookslight) will be recognized and the Bookslight version of whichClass method will be called. */ 
   public function sayClassName()
   { 
    $this->whichClass(); 
   }
} 

Bookslight extends Slightbook 
{ 
   public function whichClass() 
     { 
       echo "I am a Bookslight!.."; 
     }
}

$BookSlightObj = new Bookslight();$sbObj->sayClassName();

Out put of the above code:

I am a Bookslight!

In the code above, we create an object of the Lion class and call it $BookslightObj. And, inside the Animal class’s version of the sayClassName() function, you can see the call to $this->whichClass() due to $this pointer always references the current object, and we are dealing with an object of the Lion class above, the version of whichClass() that gets called is the one defined in the Bookslight class. This is a valid example of polymorphism in PHP.

Using “self” instead

Now, if you change “sayClassName()” function to use the self keyword instead of the $this variable, you would get a different result. Then our code now looks like this – the only change we made is highlighted in red, else is exactly the same.

Example:

class Slightbook
{ 
   public function whichClass() { 
   echo "I am a Slightbook!"; 
} 
/* This method has been changed to use the self keyword instead of $this */ 

   public function sayClassName() { 
     self::whichClass(); 
   }
}
class Lion extends Slightbook 
 {
    public function whichClass() { 
       echo "I am a BookSlight!"; 
    }
 }

$sbObj = new BookSlight();$BookSlightObj->sayClassName();

Output of the above code: 

I am a Slightbook!




Next 5 interview question(s)

1
What is the use of ::class?
2
Define inheritance and how it can be implemented in PHP?
3
What are Objects?
4
What are Classes?
5
What is an operator and how many types of operators are there?