PHP: How to instantiate a class with arguments from within another class

后端 未结 6 573
死守一世寂寞
死守一世寂寞 2021-02-07 13:48

I am in a situations where i need to instantiate a class with arguments from within an instance of another class. Here is the prototype:

//test.php

class test
{         


        
6条回答
  •  难免孤独
    2021-02-07 14:20

    The easiest way I have found:

    if ($depCount === 0) {
                $instance = new $clazz();
            } elseif ($depCount === 1) {
                $instance = new $clazz($depInstances[0]);
            } elseif ($depCount === 2) {
                $instance = new $clazz($depInstances[0], $depInstances[1]);
            } elseif ($depCount === 3) {
                $instance = new $clazz($depInstances[0], $depInstances[1], $depInstances[2]);
            }
    

    Sorry a bit raw, but you should understand the idea.

提交回复
热议问题