I want extend class which have final constructor (in my case it\'s SimpleXMLElement), but i have problems because when i use:
class myclass extends Simpl
There can be valid reasons to extend a third-party "final" class, resulting in more readable/maintainable code than completely duplicating it or creating some convoluted work-around. And certainly preferable over changing the third-party source code and removing the "final" keyword.
PHP supplies the extension "Componere" to accomplish such a feat in those rare cases where it truly is the best option. Below an example that shows how a the child class can be defined as a "trait", which can then be used to dynamically extend a final parent class:
".$this->parentvar = 'set by '.get_class().'->parentconstruct' ); }
function parentf() { echo( "\r\n
".get_class().'->parentf >> '.$this->parentvar ); }
}
/*
* Extended class members.
*/
trait ChildC /* extends ParentC */
{
function __construct() {
// Call parent constructor.
parent::__construct();
// Access an inherited property set by parent constructor.
echo( "\r\n
".get_class().'->overridden_constructor >> '.$this->parentvar );
}
function parentf() {
// Call overridden parent method.
parent::parentf();
// Access an inherited property set by constructor.
echo( "\r\n
".get_class().'->overridden_parentf >> '.$this->parentvar );
}
function dynamicf( $parm = null ) {
// Populate a parent class property.
$this->secondvar = empty( $parm ) ? 'set by '.get_class().'->dynamicf' : $parm;
// Access an inherited property set by parent constructor.
echo( "\r\n
".get_class().'->dynamicf >> '.$this->parentvar );
}
}
/*
* Register the dynamic child class "ChildC", which is
* derived by extending "ParentC" with members supplied as "ChildC" trait.
*/
$definition = new \Componere\Definition( 'ChildC', ParentC::class );
$definition->addTrait( 'ChildC' );
$definition->register();
/*
* Instantiate the dynamic child class,
* and access its own and inherited members.
*/
$dyno = new ChildC;
$dyno->parentf();
$dyno->dynamicf( 'myvalue ');
// Our object is also recognized as instance of parent!
var_dump( $dyno instanceof ChildC, $dyno instanceof ParentC, is_a( $dyno, 'ParentC') );
var_dump( $dyno );
?>