PHP - 如何检查类没有参数构造函数?

时间:2018-02-07 17:16:16

标签: php class oop arguments

在少数世界中:我想在same中使用PHP。

详细信息:我有一个Class A method来实例化Class X,可以是Class B or C

A类

class A{

   ...
   protected function init(){
       if( !empty( $this->sub_pages ) ){
           foreach ( $this->sub_pages as $sub_page ){
                $class = $sub_page['class_path'];
                //Here, I need to check if ClassX ( = $class) constructor has arguments.
                if( no arguments){
                   new $class();
                }else{
                   new $class( $sub_page['data'] );
                }
           }
       }
   }

   ...

}

B类

class B{
    public function __construct(){ //<-- No arguments

    }    
}

C类

class C extends D{
    public function __construct( $data ){ //<-- With arguments
        parent::__construct( $data );
    }    
}

有人知道答案吗?

2 个答案:

答案 0 :(得分:1)

如果你想检查一个类是否有一个构造函数,并且该构造函数是否接受任何参数,那么你可以使用PHP的{​​{3}}来完成它,例如:

$reflector = new \ReflectionClass('SomeClass');

$constructor = $reflector->getConstructor();

if ($constructor && $constructor->getParameters()) {
    // Since your class needs $sub_page['data'] and
    // you already have this in your current scope
    $instance = $reflector->newInstanceArgs($sub_page['data']);
} else {
    $instance = new SomeClass;
}

顺便说一句,如果你有类型暗示依赖项(就像其他类实例一样)那么你可以找出什么是依赖项,也可以新建那个依赖类作为参数传递。

答案 1 :(得分:0)

基于@The Alpha答案,我发现了这个:

class A{

   ...

   protected function init(){
       if( !empty( $this->sub_pages ) ){
           foreach ( $this->sub_pages as $sub_page ){
               try {
                   $reflector = new \ReflectionClass( $class );
                   if (!$constructor = $reflector->getConstructor()) {
                       printf( "The Class '%s' has not got a constructor", $class );                
                   }else {
                        // has a constructor
                        if ( $paramsArray = $constructor->getParameters() ) {
                            new $class( $sub_page['data'] );
                        }else{
                            new $class();
                        }
                    }
                } catch ( \ReflectionException $e ) {
                    echo $e;
                }

         }
     }

     ...

}