Home > PHP > PHP5 Tutorial – __autoload Magic Method

PHP5 Tutorial – __autoload Magic Method

This tutorial will guide you through the __autoload() Magic Method. The __autoload() magic method of PHP5 get automatically called whenever you try to load an object of class which resides in separate file and you have not included those files using include,require and include_once. It is recommended to use the filename as that of the class name.

Syntax:

< ?
   function __unset($classname)
   {
      require($classname.".php");
   }
//$classname is the name of the Class.
?>

Example – Basic AutoLoad Magic Method Usage

< ?
    function __autoload($classname)
    {
        include $classname.".php"; //Here $classname=magicmethod1
    }
 
    $a = new magicmethod1();
?>

Explanation for the Example:
Here i am trying to create an object of magicmethod1 class, but i have not included the magicmethod1.php so PHP compiler calls the __autoload() method which include that magicmethod1.php file.

Code for magicmethod1.php

< ?
    class magicmethod1
    {
        function __construct()
        {
            echo "MagicMethod1 Class Called";
        }
    }
?>

Output: MagicMethod1 Class Called


Custom Search

Popular Articles:

Share and Enjoy:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • email
  • IndianPad
  • LinkedIn
  • Live
  • MySpace
  • Netvibes
  • RSS
  • Technorati
  • Yahoo! Bookmarks
  • Yahoo! Buzz
  • Reddit
  • Add to favorites
  • PDF
  • Twitter
Categories: PHP Tags: ,
  1. anu
    February 12th, 2008 at 17:50 | #1

    Can you put up a tutorial on method overloading. If you’ve already explained in one of your tutorials please direct me to it.
    thanks.

  2. February 13th, 2008 at 00:13 | #2

    Hi Anu,
    You cannot do method overloading in PHP5. Please check this link:
    http://www.hiteshagrawal.com/php/oops-in-php5/php5-tutorial-not-pure-object-oriented-programming-approach

    Regards,
    Hitesh A

  3. Shailesh kumar
    July 15th, 2009 at 04:39 | #3

    Hi,

    Can you please send me the link of all the tutorial you have on php5

    thanks

  4. Nermel Gines
    October 12th, 2009 at 00:48 | #5

    everytime you call a function construct it always had __ ?
    i am confused.. or that value is a constant?

    forgive me if i ask so much question

    • November 3rd, 2009 at 02:49 | #6

      Hi Nermet,
      Calling contructor using __ is part of php syntax. It is not an constant but it inform the php to check if the name followed by __ is same as of class than it is an constructor call.

      Thanks,
      Hitesh Agarwal

  1. No trackbacks yet.