SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Enthusiast
    Join Date
    Oct 2005
    Posts
    66
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Class creation and __autoload()

    I didn't wondered one could use __autoload() to create class run-time.
    Just curious to know if someone here has already played with it.

    PHP Code:
    <?
    class VesuvianDoppleganger{
        var 
    $isDoppleganger true;    
    }

    function 
    __autoload($name){
       eval (
    '
            class '
    .$name.' extends VesuvianDoppleganger {
              var $extended =1;
            }
       '
    );

    }

    $a = new DarkElf ();

    ?><pre><?var_dump($a?></pre> <? 
    ?>

  2. #2
    SitePoint Zealot Mau's Avatar
    Join Date
    Jan 2006
    Location
    California, USA
    Posts
    134
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Sure - you can create a class at run time. But, I think this defeats the purpose of the __autoload function. You have to hard-code the classes in here. Why not just have the class already there, or include it via require?

  3. #3
    SitePoint Addict
    Join Date
    Aug 2003
    Location
    Toronto
    Posts
    300
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I think it can be handy. I have one scenario with an activerecord pattern. Custom classes that extend the base activerecord class are __autoload'ed if they exist in the filesystem; if they don't, then a stub class is generated (as in your example) that extends the base activerecord class.

    I get around hardcoding the __autoload function by using a pluggable autoload mechanism which permits multiple and customized autoload behaviours to be added programmatically.

  4. #4
    SitePoint Wizard stereofrog's Avatar
    Join Date
    Apr 2004
    Location
    germany
    Posts
    4,324
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    This technique is also useful in avoiding fatal errors in autoload.

  5. #5
    SitePoint Wizard silver trophy kyberfabrikken's Avatar
    Join Date
    Jun 2004
    Location
    Copenhagen, Denmark
    Posts
    6,157
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Interesting. I think I would favor using a factory though :
    PHP Code:
    class CritterFactory
    {
        function & 
    Create($specie) {
            switch (
    $specie) {
                case 
    'darkelf' : return new VesuvianDoppleganger();
            }
        }
    }
    $darkelf =& CritterFactory::Create('darkelf'); 


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •