PHP Trait

PHP Trait

PHP Trait is a mechanism for reusing code on a inheritance. Trait is used to reduce the limit of a inheritance by allowing developers to reuse pools methods secara mudah pada beberapa class that have different hierarchies. Trait is used to reduce complexity and avoid the same problem on multiple inheritance.

PHP Trait is similar to Class, but is only used to group functions to be the most consistent. Trait cannot stand alone. Trait is an add-on that can be added to a function without having to use the inheritance dari class lain.

Contoh penggunaan Trait :

<!–?php

trait Crud{

    function create(){

        return ‘create action’;

    }

}

trait Authentication{

    function checkLogin(){

        return ‘cek login action’;

    }

}

class Barang{

    use Crud,Authentication;

}

class Vendor{

    use Crud,Authentication;

}

$barang     = new Barang;

echo $barang->create();

echo $barang->checkLogin();

In the example above, the Barang and Vendor has no function create and checkLogin Directly. However, the code can still run without generating an error because both classes use trait named Crud and Authentication. This trait provides the implementation of the create and checkLogin, so that even though the function is not in the original definition of the Barang and Vendor, they can still take advantage of it. Thus, the use of traits allows developers to efficiently add functionality to multiple classes, without having to duplicate code or create complex inheritance hierarchies.

If in a class there is a method which is the same as Trait that is used, then the function on Class will be overwritten.

If this information is useful, don't forget to keep up with it us to get updates about the world of other interesting technologies.

Berita Rekomendasi

UMKM Saatnya Ambil Keputusan Bisnis Berdasarkan Data

21/07/2025

UMKM Saatnya Ambil Keputusan Bisnis Berdasarkan Data

Di tengah iklim ekonomi yang semakin menantang, keputusan bisnis yang hanya mengandalkan insting atau nekat bisa menjadi bumerang bagi pelaku usaha, terutama UMKM. Salah sedikit dalam menentukan produk unggulan, memprediksi…

View
Apache Airflow untuk Proses Data yang Lebih Terstruktur

12/11/2024

Apache Airflow for More Structured Data Processing

The following components of Airflow: Workloads A DAG executes a series of tasks, and there are three types of tasks in general: Control Flow DAGs are designed to run at any time, and can run in parallel....

View
Perisalah Permudah Pencatatan Rapat

09/07/2025

Perisalah Permudah Pencatatan Rapat

Di tengah persaingan bisnis yang semakin ketat, produktivitas tim menjadi kunci utama untuk menjaga kinerja dan daya saing perusahaan. Namun, realitanya, banyak waktu dan energi tim masih habis untuk pekerjaan…

View