How to access constant defined in child class from parent class functions?

后端 未结 5 1581
时光说笑
时光说笑 2021-02-03 18:37

I saw this example from php.net:



        
5条回答
  •  说谎
    说谎 (楼主)
    2021-02-03 19:03

    If you need to access constants, properties, methods of classes or objects you can use reflection, it provides much more details about structure of the object.
    example:

    class MainClass
    {
        const name = 'Primary';
    
        public $foo = 'Foo Variable';
    }
    class ExtendedClass extends MainClass
    {
        const name = 'Extended';
    }
    
    /**
     * From Class Name
     */
    
    //get reflection of main class
    $mainReflection = new ReflectionClass('MainClass');
    
    if($mainReflection->hasConstant('name'))
        var_dump($mainReflection->getConstant('name'));//Primary
    
    //get reflection of extended class
    $extendedReflection = new ReflectionClass('ExtendedClass');
    
    if($extendedReflection->hasConstant('name'))
        var_dump($extendedReflection->getConstant('name'));//Extended
    
    /**
     * From Objects
     */
    $main = new MainClass();
    $extended = new ExtendedClass();
    
    //get reflection of main class
    $mainReflection = new ReflectionObject($main);
    
    if($mainReflection->hasConstant('name'))
        var_dump($mainReflection->getConstant('name'));//Primary
    
    //get reflection of extended class
    $extendedReflection = new ReflectionObject($extended);
    
    if($extendedReflection->hasConstant('name'))
        var_dump($extendedReflection->getConstant('name'));//Extended
    

提交回复
热议问题