Partager via


Object Reference Creation

Instead of making a copy of an object, you can create a reference to the object. A reference takes less memory than an additional object, can easily be passed between procedures, and can aid in writing generic code.

Returning a Reference to an Object

Sometimes, you might want to manipulate an object by means of one or more references to the object. For example, the following program defines a class, creates an object based on the class, and returns a reference to the object:

*--NEWINV.PRG
*--Returns a reference to a new invoice form.
frmInv = CREATEOBJECT("InvoiceForm")
RETURN frmInv
 
DEFINE CLASS InvoiceForm AS FORM
   ADD OBJECT txtCompany AS TEXTBOX
   * code to set properties, add other objects, and so on
ENDDEFINE

The following program establishes a reference to the object created in Newinv.prg. The reference variable can be manipulated in exactly the same way as the object variable can:

frmInvoice = NewInv() && store the object reference to a variable
frmInvoice.SHOW

You can also create a reference to an object on a form, as in the following example:

txtCustName = frmInvoice.txtCompany
txtCustName.Value = "Fox User"

Tip   Once you've created an object, you can use the DISPLAY OBJECTS command to display the object's class hierarchy, property settings, contained objects, and available methods and events. You can fill an array with the properties (not the property settings), events, methods, and contained objects of an object with the AMEMBERS( ) function.

Releasing Objects and References from Memory

If a reference to an object exists, releasing the object does not clear the object from memory. For example, the following command releases frmInvoice, the original object:

RELEASE frmInvoice

However, because a reference to an object belonging to frmInvoice still exists, the object is not released from memory until txtCustName is released with the following command:

RELEASE txtCustName

Checking to See if an Object Exists

You can use the TYPE( ), ISNULL( ), and VARTYPE( ) functions to determine if an object exists. For example, the following lines of code check to see whether an object named oConnection exists:

IF TYPE("oConnection") = "O" AND NOT ISNULL(oConnection)
   * Object exists
ELSE
   * Object does not exist
ENDIF

Note   ISNULL( ) is necessary because .NULL. is stored to the form object variable when a user closes a form, but the type of the variable remains "O".

See Also

Writing Class Definitions Programmatically | Definition of a Grid Control | Arrays of Members and Objects | DISPLAY OBJECTS | AMEMBERS( ) | Object-Oriented Programming