Shallow Copy of an Object

Tagged:

The function below returns a shallow copy of an object based on the Empty class. Such an object can be created by SCATTER NAME or CREATEOBJECT("Empty"). A shallow copy means that any properties that hold references to other objects will be copied verbatim and as a result will be pointing to the same child objects. In other words, a shallow copy occurs when an object is copied but its contained objects are not.

This is sample code. Add error handling and adjust to your requirements as necessary.

&&FUNCTION CopyObject
LPARAMETERS toObject
LOCAL  laProps[1], lnI, loNewObject, lcPropName
&& For Empty class only
IF TYPE("toObject.Class") <> "U"
	RETURN NULL
ENDIF
loNewObject = CREATEOBJECT("Empty")
FOR lnI=1 TO AMEMBERS(laProps, toObject, 0)
	lcPropName = LOWER(laProps[lnI])
	&& Pre VFP9
	&&IF TYPE([ALEN( toObject.&lcPropName)]) = "N"
	IF TYPE([toObject.] + lcPropName,1) = "A"
		&& Array
		ADDPROPERTY(loNewObject, lcPropName + "[1]", NULL )
		= ACOPY(toObject.&lcPropName, loNewObject.&lcPropName)
	ELSE
		ADDPROPERTY(loNewObject, lcPropName, EVALUATE("toObject." + lcPropName) )
	ENDIF	
ENDFOR
 
RETURN loNewObject