Minggu, 01 Juni 2014

Trait php

Traits are a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies. The semantics of the combination of Traits and classes is defined in a way which reduces complexity, and avoids the typical problems associated with multiple inheritance and Mixins.


trait atau sifat / ciri adalah fungsi baru yang ada php 5.4.0 yang resmi dirilis pada 1 maret 2012. Sifat / ciri tersebut mempunyai kesamaan dengan class tetapi hanya dapat di muat oleh function atau fungsi . Lebih jelasnya lagi mari membuat contoh script menggunakan trait.


<?phptrait ezcReflectionReturnInfo {
    function 
getReturnType() { /*1*/ }
    function 
getReturnDescription() { /*2*/ }
}

class 
ezcReflectionMethod extends ReflectionMethod {
    use 
ezcReflectionReturnInfo;
    
/* ... */}

class 
ezcReflectionFunction extends ReflectionFunction {
    use 
ezcReflectionReturnInfo;
    
/* ... */}?>

<?phpclass Base {
    public function 
sayHello() {
        echo 
'Hello ';
    }
}

trait 
SayWorld {
    public function 
sayHello() {
        
parent::sayHello();
        echo 
'World!';
    }
}

class 
MyHelloWorld extends Base {
    use 
SayWorld;
}
$o = new MyHelloWorld();$o->sayHello();?>
 Output :
Hello World!
 

Tidak ada komentar:

Posting Komentar