dongxiangchan0743 2010-12-29 15:05
浏览 90
已采纳

使用两个同名的类

I have two PHP apps which have twho class with the same name. - app1 with a class "Project" - app2 with a class "Project"

I have to use classes of the first app in the second one, but two class with one name cause an error ("PHP Fatal error: Cannot redeclare class Project ...").

I can't change class names. I have to use PHP 5.2 (no namespace in PHP 5.2).

Is there a solution ?

May be :

  • use the class Project
  • undef this class (kind of "unset Project", is it possible with PHP ?)
  • include() the 2nd class
  • use the 2nd class

I don't know if it's possible with PHP (don't find any ressource about this) and I don't know a better way to manage this ...

  • 写回答

3条回答 默认 最新

  • drll85318 2012-04-07 05:57
    关注

    I had this problem recently, with (embarrassingly) Joomla. I needed to find the versions of two different installations with one script, by loading up their two "version.php" files and then reading the class properties. But, of course, they're both called "JVersion", and it's impossible to require() both version.php files because of it.

    After much thought, I realized eval() could take the place of require(). So I just read in the contents of the version.php files and change the names of the classes, then eval() that text, and then I can access both classes with different names. I bet you'd like some code. Here's what I ended up with...

    
    
        $v15_txt=file_get_contents($old_dir.'/libraries/joomla/version.php');
        $v15_txt=preg_replace('/class JVersion/i', 'class JVersion15', $v15_txt);
        eval('?>'.$v15_txt);
        $jvold=new JVersion15;
        $old_version = $jvold->RELEASE.'.'.$jvold->DEV_LEVEL;
    
        $v25_txt=file_get_contents($new_dir.'/libraries/cms/version/version.php');
        $v25_txt=preg_replace('/class JVersion/i', 'class JVersion25', $v25_txt);
        eval('?>'.$v25_txt);
        $jvnew=new JVersion25;
        $new_version = $jvnew->RELEASE.'.'.$jvnew->DEV_LEVEL;
    
    
    

    Just modify it so it loads the right two files for your needs and renames them as required. Sorry you had to wait over a year for it. :-)

    It's hard to believe PHP doesn't have some kind of "undeclare($classname)" function built-in. I couldn't even solve this with namespacing, because that requires changing the original two files. Sometimes ya just gotta think outside the framework.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题