dstwfcz1377 2015-03-31 10:09
浏览 85
已采纳

如何在PHP中模块化类方法?

I an new in OOP in PHP.

I am looking for a best practice how the modularize a php class. What I want is to define my class and then "load" methods for this class by including php files.

Here is some code to illustrate what I mean:

<?php /* module.php */

class MyClass_Module {

    public function foo(){
        print_r("Hello welt");
    }

}

<?php /* somewhere else */

class MyClass {

    function __construct($optionen = array()){
        require_once("module.php");
    }


}

$myObj = new MyClass();
$myObj->foo();
  • 写回答

4条回答 默认 最新

  • doushi5024 2015-03-31 11:43
    关注

    I found the solution by using traits:

    <?php /* module.php */
    
    trait MyClass_Module {
    
        public function foo(){
            print_r("Hallo Welt");
        }
    
    }
    
    
    <?php /* somewhere else */
    
    require_once("module.php");
    
    class MyClass {
    
        use MyClass_Module;
    
    }
    
    $myObj = new MyClass();
    
    $myObj->foo();
    

    Thanks to all who gave me answers – I have learned a lot by looking at your suggestions.

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

报告相同问题?

悬赏问题

  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作