Invalid use of the THIS
keyword
The THIS
keyword provides access to the current instance of a FUNCTION_BLOCK
. However, there are several rules governing its proper use:
Common errors
-
Using
THIS
outside of aFUNCTION_BLOCK
context: TheTHIS
keyword can only be used inside aFUNCTION_BLOCK
or itsMETHOD
s orACTION
s. It cannot be used inFUNCTION
s,PROGRAM
s, or . -
Not dereferencing
THIS
to access members: When accessing members usingTHIS
, it must be dereferenced using the^
operator:THIS^.member
. -
Member access position:
THIS
cannot be accessed as a member of another object. Expressions likex.THIS^
are invalid. -
Global access position:
THIS
cannot be used with the global access operator (.THIS^.member
). -
Using
THIS
with type cast operators: The type cast operator (<type>#
) cannot be used withTHIS
.
Examples of invalid use
// Error: Using THIS outside `FUNCTION_BLOCK` context
FUNCTION func
THIS^.x := 2; // Error: Invalid use of `THIS`
END_FUNCTION
// Error: Not dereferencing THIS when accessing members
FUNCTION_BLOCK fb
THIS.x := 20; // Error: `THIS` must be dereferenced to access its members
END_FUNCTION_BLOCK
// Error: THIS in member access position
FUNCTION_BLOCK fb
x.THIS^.y := 20; // Error: `THIS` is not allowed in member-access position
END_FUNCTION_BLOCK
// Error: Global access position
FUNCTION_BLOCK fb
.THIS^.x := 20; // Error: `THIS` is not allowed in global-access position
END_FUNCTION_BLOCK
// Error: Using THIS with type cast
FUNCTION_BLOCK fb
p := fb#THIS; // Error: The `<type>#` operator cannot be used with `THIS`
END_FUNCTION_BLOCK
Examples of valid use
FUNCTION_BLOCK Counter
VAR
count : INT;
enabled : BOOL;
END_VAR
// Valid: Direct use in FUNCTION_BLOCK implementation
METHOD increment
IF THIS^.enabled THEN
THIS^.count := THIS^.count + 1;
END_IF
END_METHOD
// Valid: Using THIS to pass the instance to another FB
METHOD send_to_logger : BOOL
VAR_IN_OUT
logger : Logger;
END_VAR
logger.log_counter(THIS);
END_METHOD
// Valid: Using THIS to compare with another instance
METHOD equals : BOOL
VAR_IN_OUT
other : Counter;
END_VAR
equals := THIS^.count = other.count;
END_METHOD
ACTION my_action
IF THIS^.enabled THEN
THIS^.count := THIS^.count + 1;
END_IF
END_ACTION
END_FUNCTION_BLOCK