I want to write a method which resets an abject to its initial state by unsetting all properties except those set in the constructor.

How do I get all the properties in an object so I can loop through them?

Thanks

voidstate

    It might be possible with the reflection features introduced in PHP5, but a more normal approach would simply be to define the method and manually unset the required properties.

      The reset method will reside in the parent, though, so won't know what properties to unset...

        The reset method will reside in the parent, though, so won't know what properties to unset...

        The child classes can override the parent's reset() method.

          Found it: get object vars()

          Thanks for helping laserlight.

            Found it: get object vars()

            Interesting. However, that will not work within a method of the class. You would have to call it from outside the class. If you call it on $this, you risk getting an incomplete set of member variables.

              It appears to work fine. Here's my method, in case anyone's interested.

              function reset()
              {
              	$current_properties = get_object_vars( $this );
              	$default_properties = get_class_vars( get_class( $this ) );
              	if( empty( $default_properties ) )
              		$default_properties = array();
              
              foreach( $current_properties as $property => $value )
              {
              	if( !key_exists( $property, $default_properties ) ) // unset
              	{
              		unset( $this->{ $property } );
              	}
              	elseif( $property != 'DbAccess' && $property != 'UriManager' ) // reset
              	{
              		$this->{ $property }  =  $default_properties[ $property ];
              	}
              }
              }

              voidstate

                Write a Reply...