2024 年 PHP Conference Japan

Componere\Definition 類別

(Componere 2 >= 2.1.0)

簡介

Definition 類別允許程式設計師在執行階段建構和註冊類型。

如果 Definition 取代了現有的類別,則在 Definition 銷毀時將會還原現有的類別。

類別概要

final class Componere\Definition extends Componere\Abstract\Definition {
/* 建構函式 */
public __construct(string $name)
public __construct(string $name, string $parent)
公開 __construct(字串 $name, 陣列 $interfaces)
公開 __construct(字串 $name, 字串 $parent, 陣列 $interfaces)
/* 方法 */
公開 addConstant(字串 $name, Componere\Value $value): 定義
公開 addProperty(字串 $name, Componere\Value $value): 定義
公開 register():
公開 getClosure(字串 $name): 閉包
/* 繼承方法 */
}

目錄

新增註解

使用者貢獻的註解 1 則註解

ASchmidt at Anamera dot net
6 年前
有時我們可能希望擴展一個被定義為「final」的第三方類別。

在此範例中,子類別將擴展一個「final」類別,並新增一個方法。物件實例將能夠存取父成員,並且會被識別為動態建立的子類別及其父類別的實例。

<?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 ); }
}

/*
* Dynamically define a child class "DynamicC"
* which successfully extends final class "ParentC".
*/
$DefC = new \Componere\Definition( 'DynamicC', 'ParentC');

// Extend child class with method 'DynamicC::dynamicf()'.
$DefM = new Componere\Method( function( $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 );
} );
$DefC->addMethod( 'dynamicf', $DefM );

// Take dynamic child class 'life'.
$DefC->register();

/*
* Instantiate the dynamic child class,
* and access its own and inherited members.
*/

$dyno = new DynamicC;
$dyno->parentf();
$dyno->dynamicf( 'myvalue ');

// Our object is also recognized as instance of parent!
var_dump( $dyno instanceof DynamicC, $dyno instanceof ParentC );
var_dump( $dyno );
%>

will output:

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)
To Top