Search code examples
phpclassmediawikiphpbb

Possible to dynamically set the name of a class?


I have a mediawiki and phpbb install that I integrated single sign on with successfully.

The problem was that they both had a user class, so in mediawiki, when I called on phpbb it gave a class redecoration error.

I got around this by checking if the file is being loaded by mediawiki. If it is, it called a complete copy of the user class called phpbb_user instead. But I'm wondering if there is a better way. This is how it currently works

if (!defined('FROM_MEDIAWIKI')){
    class User extends session{
    //user class code
    }

}else{
    class phpbb_user extends session{
    //exact copy of user class code
    }

}

Is there a better way to do this that does not require 2 copies of the user class?

I know you can not do this but can you do something like it?

$className = (defined('FROM_MEDIAWIKI'))? 'phpbb_user' : 'User';

class $className extends session{
    //user class code
}

Solution

  • This is a bit of a hack, but you could have a base class, where everything if defined. Then you simply extend empty subclasses from that class, thus changing its name without having to keep duplicate code.

    class __user extends session {
        // user class code
    }
    
    if (!defined('FROM_MEDIAWIKI')){
        class User extends __user {}
    }else{
        class phpbb_user extends __user {}
    }
    

    I'd love to see a better solution, though.