Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Magic Methods in PHP

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 182
    Comment on it

    PHP does not provide any specific definitions of the magic methods or functions. It is the programmer who actually writes the code to the functions that defines which states what the magic functions will do. But, magic functions are not directly called by the programmers, instead PHP calls the function 'behind the scenes'. This is why they are called “magic functions”. Some of the magic functions that are available in the PHP are __construct(), __destruct(), call(), callStatic(), __get(), __set(), __isset(), __unset(), __sleep(), __wakeup(), __toString(), __invoke(), __set_state(), __clone(), and __autoload().

     

    Here we will discuss about the __construct() and __destruct() functions:

     

    1. __construct():the most commonly used magic function __construct() was introduced because as of PHP version 5, it is basically the constructor for our class. It is called automatically whenever a new object is created.
    2. __destruct() :this method is useful in cleaning up the class ,for instance, closing a database connection. It can be called up either expressly by us or when we are not using an object anymore. PHP cleans it for us.

     

    <?php
    
    class MyClass
    {
      public $property1 = "I'm a class property!";
    
      public function __construct()
      {
       echo 'The class "', __CLASS__, '" was initiated!<br />';
      }
    
      public function __destruct()
      {
        echo 'The class "', __CLASS__, '" was destroyed.<br />';
      }
    
      public function setProperty($newvalue)
      {
        $this->property1 = $newvalue;
      }
    
      public function getProperty()
      {
       return $this->property1 . "<br />";
      }
    }
    
    $obj = new MyClass;         // Create a new object
    
    echo $obj->getProperty();  // Get the value of $prop1
    
    echo "End of file.<br />"; // Output a message at the end of the file
    
    ?>

     

    OUTPUT:

    The class "MyClass" was initiated!
    I'm a class property!
    End of file.
    The class "MyClass" was destroyed.

     

    __CLASS__ is a magic constant which is used to return the name of the class in which it is called.

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: