除了可通过 EXTENDS
进行扩展外,通过使用接口和继承也可支持使用功能块执行面向对象的编程。这需要动态解析的方法调用,也称为虚拟功能调用。
虚拟功能调用需要比普通功能调用更多的时间,并在以下情况使用:
通过指向功能块 (pfub
^.method) 的指针执行调用
调用了接口变量的方法 (interface1.method)
方法调用同一功能块的另一个方法
通过对于功能块的引用执行调用
可向基本功能块类型的 VAR_IN_OUT
分配衍生的功能块类型的实例
虚拟功能调用可让程序源代码中的同一调用在运行时期间调用不同方法。
有关更多信息和深入说明,请参阅:
根据 IEC 61131-3 标准,诸如普通功能等方法可具有额外输出。可以根据语法在方法调用中分配它们:
<方法>(in1:=<值> |, 更多输入分配, out1 => <输出变量 1> | out2 => <输出变量 2> | ...更多输出变量)
这样的作用是将方法的输出写入在调用中提供的本地声明的变量。
假设功能块 fub1
和 fub2
EXTEND
功能块 fubbase
和 IMPLEMENT
interface1
。包含有方法 method1
。
可使用接口和方法调用:
PROGRAM PLC_PRG
VAR_INPUT
b : BOOL;
END_VAR
VAR
pInst : POINTER TO fubbase;
instBase : fubbase;
inst1 : fub1;
inst2 : fub2;
instRef : REFERENCE to fubbase;
END_VAR
IF b THEN
instRef REF= inst1; (* Reference to fub1 *)
pInst := ADR(instBase);
ELSE
instRef REF= inst2; (* Reference to fub2 *)
pInst := ADR(inst1);
END_IF
pInst^.method1(); (* If b is true, fubbase.method1 is called, else fub1.method1 is called *)
instRef.method1(); (* If b is true, fub1.method1 is called, else fub2.method1 is called *)
假设上面示例中的 fubbase
包含 2 个方法 method1
和 method2
。fub1
覆盖 method2
,但不覆盖 method1
。
如上面示例中所示,调用了 method1
。
pInst^.method1(); (* If b is true fubbase.method1 is called, else fub1.method1 is called *)
对于通过 THIS 指针调用,请参阅 THIS 指针。