Get string within protected object

后端 未结 4 992
庸人自扰
庸人自扰 2020-12-21 05:45

I am trying to get the the string \"this info\" inside this object lets call it $object, but data is protected, how can I access that pocket?

           


        
4条回答
  •  感情败类
    2020-12-21 06:15

    To retrieve a protected property you can use the ReflectionProperty interface.

    The phptoolcase has a fancy method for this task:

    public static function getProperty( $object , $propertyName )
            {
                if ( !$object ){ return null; }
                if ( is_string( $object ) ) // static property
                {
                    if ( !class_exists( $object ) ){ return null; }
                    $reflection = new \ReflectionProperty( $object , $propertyName );
                    if ( !$reflection ){ return null; }
                    $reflection->setAccessible( true );
                    return $reflection->getValue( );
                }
                $class = new \ReflectionClass( $object );
                if ( !$class ){ return null; }
                if( !$class->hasProperty( $propertyName ) ) // check if property exists
                {
                    trigger_error( 'Property "' . 
                        $propertyName . '" not found in class "' . 
                        get_class( $object ) . '"!' , E_USER_WARNING );
                    return null;
                }
                $property = $class->getProperty( $propertyName );
                $property->setAccessible( true );
                return $property->getValue( $object );
            }
    
    
    $value = PtcHandyMan::getProperty( $your_object , ‘propertyName’);
    
    $value = PtcHandyMan::getProperty( ‘myCLassName’ , ‘propertyName’); // singleton
    

提交回复
热议问题