有时我们可能希望扩展一个定义为“final”的第三方类。
在这个例子中,子类将扩展“final”类,添加一个方法。对象实例将能够访问父类成员,并且被识别为动态创建的子类及其父类的实例。
<?php
declare(strict_types=1);
final class ParentC
{
public $parentvar;
public $secondvar;
function __construct() { echo( "\r\n<br/>".$this->parentvar = 'set by '.get_class().'->parentconstruct' ); }
function parentf() { echo( "\r\n<br/>".get_class().'->parentf >> '.$this->parentvar ); }
}
$DefC = new \Componere\Definition( 'DynamicC', 'ParentC');
$DefM = new Componere\Method( function( $parm = null ) {
$this->secondvar = empty( $parm ) ? 'set by '.get_class().'->dynamicf' : $parm;
echo( "\r\n<br/>".get_class().'->dynamicf >> '.$this->parentvar );
} );
$DefC->addMethod( 'dynamicf', $DefM );
$DefC->register();
$dyno = new DynamicC;
$dyno->parentf();
$dyno->dynamicf( 'myvalue ');
var_dump( $dyno instanceof DynamicC, $dyno instanceof ParentC );
var_dump( $dyno );
%>
将输出:
set by ParentC->parentconstruct
ParentC->parentf >> set by ParentC->parentconstruct
DynamicC->dynamicf >> set by ParentC->parentconstruct
(boolean) true
(boolean) true
object(DynamicC)
public 'parentvar' => string 'set by ParentC->parentconstruct' (length=31)
public 'secondvar' => string 'myvalue ' (length=8)