dongyanjing5975 2011-06-06 22:57
浏览 95
已采纳

php oop类调用内部函数

so i have a class which contains basic stuff like

Class Test{
   public function wheels(){
        echo 'wheels';
   }
}

and another one

Class Test2{
   public function bikes(){
       $test = new Test();
       return 'i am a bike with '.$test;
   }
}

so my question is if i have different classes that i need inside a function is it good practise to call it like $var = new ClassName();

or there is a better way to call different classes inside classes functions?

  • 写回答

6条回答 默认 最新

  • dthtvk3666 2011-06-06 23:14
    关注

    For your webapp write an autoloader that is just loading all classes from files you want to use while you need it.

    You can then just write the code like you want to w/o the need to build complex inheritance between classes only because you want to make use of the functionality you've coded.

    This has multiple benefits:

    1. Even w/o much experience in OOAD you keep stuff apart from each other by not introducing much relationship between multiple classes. Relationship between classes can be bad because you make things dependable on each other when it's not really needed.
    2. You can easily extend and change your application. That's important as you continue to code, be it now or later.

    That's just my 2 cents. If you don't like autoloader later on, you can change that, too. But it helps to get things on the run straight-forward.

    Example:

    function my_autoloader_function($name) {
        require(sprintf('%s/%s.php', $yourlibfolderdir, $name));
    }
    spl_autoload_register('my_autoloader_function');
    // [...] (even in other files)
    $obj = new Test5;
    $obj->funcZalabri();
    

    The registered autoloader function will be called each time a class is instantiated/accesses while it does not exists. In the example it's assumed that there is one class per file which is quite common and in my opinion very nice to manage the code.

    As the autoloader is a callback and it's written in PHP you can do whatever you want in it and make it much more detailed to fit your needs.

    Hope this helps.

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

报告相同问题?

悬赏问题

  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch