Technical interview questions for software engineers — languages, databases, web, cloud, DevOps, and fundamentals. Browse all topics.

  • PHP Interview Questions

  • OOP Interview Questions

  • jQuery Interview Questions

  • MySQL Interview Questions

  • JavaScript Interview Questions

  • HR Interview Questions

  • HTML Interview Questions

  • C/C++ Interview Questions

  • Showing posts with label constructor. Show all posts
    Showing posts with label constructor. Show all posts

    Constructor and Desctructor.

    Constructor:


    PHP 5 allows developers to declare constructor methods for classes.Classes call constructor method on each newly-created object. 
    function __construct() {
    //
    }
    Example:


    <?php
    class MainClass {
       function __construct() {
          echo "In MainClass constructor\n";
       }
    }


    class ChildClass extends MainClass {
       function __construct() {
           parent::__construct();
          echo "In SubClass constructor\n";
       }
    }


    $obj = new MainClass();
    $obj = new SubClass();
    ?>
    Note: If  PHP 5 cannot find a __construct() function for a given class, it will search for the old constructor function, by the name of the class. 


    Destructor:


    The destructor method will be called as soon as Classes destroy the object.


     function __destruct() {
      //     
       }
    Example:


    <?php
    class MainClass {
       function __construct() {
          echo "In MainClass constructor\n";
       }
    function __destruct() {
           print "Destroying \n";
       }
    }
    class ChildClass extends MainClass {
       function __construct() {
           parent::__construct();
          echo "In SubClass constructor\n";
       }
       
    }


    $obj = new MainClass();
    $obj = new SubClass();
    ?>


    Note:The destructor method will be called even if script execution is stopped using exit().


    Bookmark and Share

    How do you call a constructor for a parent class?

    base class,constructor,call,parent class,PHP, Question, call constructor from parent,PHP: Calling Parent Class Constructors,class Parent
    How do you call a constructor for a parent class? 


    parent::constructor($value)


    Example:



    class parentClass
    {
         function __construct()
       {
        }
    }


    class chClass extends parentClass
    {
       function __construct()
       {
          parent::__construct(); //call a constructor for a parent class
           }
    }






    Bookmark and Share