• Explain abstract class and its behaviour?

      0 comments

    Abstract class is defined as a solitary entity, so other classes can inherit from it. An abstract  class can not be instantiated, only the subclasses of it can have instances. Following is one of the best examples to explain the use of an abstract class and the behavior of it.

     class Fruit {
     private $color;
    
     public function eat() {
      //chew
     }
    
      public function setColor($c) {
       $this->color = $c;
      }
     }
    
     class Apple extends Fruit {
      public function eat() {
       //chew until core
      }
     }
    
     class Orange extends Fruit {
      public function eat() {
       //peel
       //chew
      }
     }
    

    Now taste an apple

    $apple = new Apple();
    $apple->eat();
    

    What’s the taste of it? Obviously it’s apple

    Now eat a fruit

    $fruit = new Fruit();
    $fruit->eat();
    

    What’s the taste of it? It doesn’t make any sense. does it? Which means the class fruit should not be Instantiable . This is where the abstract class comes into play

    abstract class Fruit {
     private $color;
    
     abstract public function eat()
    
     public function setColor($c) {
      $this->color = $c;
     }
    }
    

  • Write a small function to calculate n to the power of n?

      0 comments

    In the above question the interviewer is expecting the logic behind the scene (Recursive). Actually he may directly ask you to write a recursive function to calculate N to the power of N, or given number to the power of N. Following is the simplest way that you can write a PHP recursive function for this functionality.

    
    function MyPow($r, $w){
     if($w==0)
      return 1;
     else
      return MyPow($r, $w-1) * $r;
    }
    
    echo MyPow(10, 2);
    

    Also this functionality substitutes by the pow() function in PHP.