PHPのお勉強!

PHP TOP

Componere\Abstract\Definition::addTrait

(Componere 2 >= 2.1.0)

Componere\Abstract\Definition::addTraitAdd Trait

説明

public Componere\Abstract\Definition::addTrait(string $trait): Definition

Shall use the given trait for the current definition

パラメータ

trait

The case insensitive name of a trait

戻り値

The current Definition

Exceptions

警告

Shall throw RuntimeException if Definition was registered

add a note

User Contributed Notes 1 note

up
0
ASchmidt at Anamera dot net
6 years ago
Adding a trait is an efficient way to extend a "final" class, overriding methods and adding new ones, without having to individually add each method as a closure. It also results in more readable code.

<?php
declare(strict_types=1);

/*
* Final class would normally prevent extending.
*/
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 ); }
}

/*
* 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<br/>".get_class().'->overridden_constructor >> '.$this->parentvar );
}

function
parentf() {
// Call overridden parent method.
parent::parentf();
// Access an inherited property set by constructor.
echo( "\r\n<br/>".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<br/>".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 );
?>

will output:

set by ParentC->parentconstruct
ChildC->overridden_constructor >> set by ParentC->parentconstruct
ParentC->parentf >> set by ParentC->parentconstruct
ChildC->overridden_parentf >> set by ParentC->parentconstruct
ChildC->dynamicf >> set by ParentC->parentconstruct

boolean true
boolean true
boolean true

object(ChildC)[2]
public 'parentvar' => string 'set by ParentC->parentconstruct' (length=31)
public 'secondvar' => string 'myvalue ' (length=8)
To Top