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条)

报告相同问题?