xHarbour Reference Documentation > Statement Reference xHarbour Developers Network  

EXTEND CLASS...WITH METHOD

Adds a new method to an existing class.

Syntax

EXTEND CLASS <ClassName>    WITH ;
   [ MESSAGE <MessageName>] METHOD <FunctionName>

or

EXTEND CLASS <ClassName>    WITH ;
     MESSAGE <MessageName>  INLINE <expression>

Arguments

<ClassName>
This is the symbolic name of an existing class to add a new method to.
MESSAGE <MessageName>
This is the symbolic name of the message which invokes the new method.
METHOD <FunctionName>
This is the symbolic name of the function implementing the code for the new method. If <MessageName> is omitted, <FunctionName> defines also the message that must be sent to an object for invoking the method.
INLINE <expression>
This is the expression which is executed when an INLINE method is invoked. <expression> must be one line of code. The code cannot contain commands but only function and method calls.

Description

The EXTEND CLASS...WITH METHOD statement allows for adding new methods to a declared class outside the class declaration. This way, a class can be enhanced even if the source code of the class is not available. The EXTEND CLASS statemend can modify all classes existing in xHarbour.

The new method is either implemented as a STATIC FUNCTION or as an INLINE expression. The self object is retrieved in both cases with function HB_QSelf().

Note:  an alternative for enhancing an existing class is to use the FROM option of the CLASS statement and create a sub-class of an existing class.

Info

See also:ASSOCIATE CLASS, CLASS, EXTEND CLASS...WITH DATA, HB_QSelf(), METHOD...OPERATOR, OPERATOR, OVERRIDE METHOD
Category: Class declaration , Declaration , xHarbour extensions
Header:hbclass.ch
Source:vm\classes.c
LIB:xhb.lib
DLL:xhbdll.dll

Example

// The example adds a method to the "root" class of xHarbour: HBObject().
// All new classes inherit from this class. This is used in the example
// for tracing variables depending on their data types in different log
// files.

   #include "HbClass.ch"

   PROCEDURE Main
      LOCAL obj, nValue := 2, dDate := Date()

      EXTEND CLASS HBObject WITH MESSAGE log METHOD LogData

      ENABLE TYPE CLASS ALL

      obj := Test():new( "xHarbour" )

      obj:log( "Objects.log" )

      nValue:log( "Numerics.log" )

      dDate:log( "Dates.log" )
   RETURN


   CLASS Test
      EXPORTED:
      DATA value
      METHOD init(x) INLINE (::value := x, self)
   ENDCLASS


   STATIC FUNCTION LogData( cLogFile )
      LOCAL self := HB_QSelf()
      LOCAL cOldFile

      IF .NOT. Set( _SET_TRACE )
         RETURN self
      ENDIF

      IF Valtype( cLogFile ) == "C"
         cOldFile := Set( _SET_TRACEFILE, cLogFile )
      ENDIF

      Tracelog( self )

      IF cOldFile <> NIL
         Set( _SET_TRACEFILE, cOldFile )
      ENDIF
   RETURN self

Copyright © 2006-2007 xHarbour.com Inc. All rights reserved.
http://www.xHarbour.com
Created by docmaker.exe