Dapatkah suatu sifat menggunakan php sifat lain?

Ciri-ciri PHP menyediakan cara mudah untuk berbagi metode antar kelas. Namun ada kalanya kita mungkin perlu mengganti atau memperluas metode yang ditentukan dalam sifat yang melekat pada kelas. Mari kita lihat bagaimana kita bisa mencapai ini

Mari kita mulai dengan mendefinisikan sifat yang sangat sederhana sebagai contoh yang disebut FooTrait yang berisi definisi metode publik yang disebut bar(). -

trait FooTrait { public function bar() { return 'A'; } }

Kami kemudian dapat menetapkan sifat itu ke kelas dan memanggil bar() sebagai metode kelas. -

class Example { use FooTrait; } echo (new Example())->bar(); // Outputs 'A'_

Metode sifat terlampir pada dasarnya berfungsi seolah-olah telah disalin dan ditempelkan ke kelas Example kami

Jika kita kemudian mendefinisikan metode bar() baru di kelas Example kita yang akan menggantikan metode bar() sifat, maka metode baru ini akan dijalankan sebagai gantinya. -

class Example { use FooTrait; public function bar() { return 'B'; } } echo (new Example())->bar(); // Outputs 'B'

Ini mencakup mengesampingkan metode suatu sifat, tetapi bagaimana jika kita ingin memperpanjang metode daripada menggantinya? . Dengan mendefinisikan bar() di kelas kami, ini telah menggantikan metode bar() yang didefinisikan dalam FooTrait terlampir. Oleh karena itu, jika kita ingin memperluas metode yang didefinisikan dalam sifat kita dari kelas kita, kita perlu mengganti nama metode bar() sifat itu menjadi sesuatu seperti class Example { use FooTrait; } echo (new Example())->bar(); // Outputs 'A'7 di kelas kita dan kemudian langsung memanggil class Example { use FooTrait; } echo (new Example())->bar(); // Outputs 'A'8 di dalam metode bar() kelas kita seperti ini. -

class Example { use FooTrait { bar as traitBar; } public function bar() { return $this->traitBar() . 'B'; } } echo (new Example())->bar(); // Outputs 'AB'_

Dengan cara ini kita dapat memperluas metode dengan cara yang mirip dengan memperluas metode kelas yang diwariskan. Mengganti nama metode sifat seperti ini juga berguna saat melampirkan beberapa sifat ke kelas di mana mungkin ada konflik dalam nama metode

Jadi begitulah, kami telah melihat bagaimana kami dapat mengganti dan memperluas metode sifat. Ciri-ciri adalah cara yang berguna untuk menjaga kode kita KERING (mis. e. tidak mengulangi diri kita sendiri) dan berbagi metode di antara kelas. Fakta bahwa kita dapat mengesampingkan dan memperluas metode dari suatu sifat membuatnya sangat berguna

Ringkasan. dalam tutorial ini, Anda akan mempelajari cara menggunakan ciri-ciri PHP untuk berbagi fungsionalitas di seluruh kelas independen, yang tidak berada dalam hierarki pewarisan yang sama

Pengantar ciri-ciri PHP

Penggunaan kembali kode adalah salah satu aspek terpenting dari pemrograman berorientasi objek. Di PHP, Anda menggunakan pewarisan untuk mengaktifkan penggunaan kembali kode di kelas yang berbeda dengan hierarki pewarisan yang sama

Untuk mencapai penggunaan kembali kode, Anda memindahkan fungsionalitas umum kelas ke metode kelas induk. Namun, warisan membuat kode digabungkan dengan sangat erat. Oleh karena itu, penggunaan warisan yang berlebihan dapat menyebabkan kode sangat sulit dipertahankan

Untuk mengatasi masalah ini, PHP 5. 4 memperkenalkan unit kode baru yang dapat digunakan kembali yang disebut trait. Ciri-ciri memungkinkan Anda untuk menggunakan kembali berbagai metode secara bebas di banyak kelas berbeda yang tidak perlu berada dalam hierarki kelas yang sama

Warisan memungkinkan kelas menggunakan kembali kode secara vertikal sementara sifat memungkinkan kelas menggunakan kembali kode secara horizontal

Sifat mirip dengan kelas, tetapi hanya untuk mengelompokkan metode dengan cara yang halus dan konsisten. PHP tidak mengizinkan Anda untuk membuat turunan dari Trait seperti turunan dari kelas. Dan tidak ada konsep turunan dari suatu sifat

Contoh Sifat PHP

Untuk mendefinisikan suatu sifat, Anda menggunakan kata kunci sifat diikuti dengan nama sebagai berikut

<?php trait Logger { public function log($msg) { echo '<pre>'; echo date('Y-m-d h:i:s') . ':' . '(' . __CLASS__ . ') ' . $msg . '<br/>'; echo '</pre>'; } }

Code language: HTML, XML (xml)

Untuk menggunakan sifat di kelas, Anda menggunakan kata kunci use. Semua metode sifat tersedia di kelas tempatnya digunakan. Memanggil metode suatu sifat mirip dengan memanggil metode instan

Contoh berikut menunjukkan cara menggunakan sifat Logger di kelas

class BankAccount { use Logger; private $accountNumber; public function __construct($accountNumber) { $this->accountNumber = $accountNumber; $this->log("A new $accountNumber bank account created"); } }

Code language: PHP (php)0

class BankAccount { use Logger; private $accountNumber; public function __construct($accountNumber) { $this->accountNumber = $accountNumber; $this->log("A new $accountNumber bank account created"); } }

Code language: PHP (php)_

Dan Anda dapat menggunakan kembali sifat Logger_ di kelas

class BankAccount { use Logger; private $accountNumber; public function __construct($accountNumber) { $this->accountNumber = $accountNumber; $this->log("A new $accountNumber bank account created"); } }

Code language: PHP (php)2 sebagai berikut

class User { use Logger; public function __construct() { $this->log('A new user created'); } }

Code language: PHP (php)

Kedua kelas

class BankAccount { use Logger; private $accountNumber; public function __construct($accountNumber) { $this->accountNumber = $accountNumber; $this->log("A new $accountNumber bank account created"); } }

Code language: PHP (php)0 dan

class BankAccount { use Logger; private $accountNumber; public function __construct($accountNumber) { $this->accountNumber = $accountNumber; $this->log("A new $accountNumber bank account created"); } }

Code language: PHP (php)2 menggunakan kembali metode dari sifat Logger, yang sangat fleksibel

Menggunakan beberapa sifat

Kelas dapat menggunakan beberapa ciri. Contoh berikut menunjukkan cara menggunakan beberapa ciri di kelas IDE. Ini mensimulasikan model kompilasi C di PHP demi demonstrasi

<?php trait Preprocessor { public function preprocess() { echo 'Preprocess...done' . '<br/>'; } } trait Compiler { public function compile() { echo 'Compile code.. done' . '<br/>'; } } trait Assembler { public function createObjCode() { echo 'Create the object code files.. done.' . '<br/>'; } } trait Linker { public function createExec() { echo 'Create the executable file...done' . '<br/>'; } } class IDE { use Preprocessor, Compiler, Assembler, Linker; public function run() { $this->preprocess(); $this->compile(); $this->createObjCode(); $this->createExec(); echo 'Execute the file...done' . '<br/>'; } } $ide = new IDE(); $ide->run();

Code language: HTML, XML (xml)

Menyusun beberapa sifat

PHP memungkinkan Anda menyusun beberapa sifat menjadi suatu sifat dengan menggunakan pernyataan use dalam deklarasi sifat. Sebagai contoh

<?php trait Reader { public function read($source) { echo sprintf('Read from %s <br>', $source); } } trait Writer { public function write($destination) { echo sprintf('Write to %s <br>', $destination); } } trait Copier { use Reader, Writer; public function copy($source, $destination) { $this->read($source); $this->write($destination); } } class FileUtil { use Copier; public function copyFile($source, $destination) { $this->copy($source, $destination); } }

Code language: HTML, XML (xml)

Bagaimana itu bekerja

  • Pertama, tentukan sifat

    class BankAccount { use Logger; private $accountNumber; public function __construct($accountNumber) { $this->accountNumber = $accountNumber; $this->log("A new $accountNumber bank account created"); } }

    Code language: PHP (php)7 dan

    class BankAccount { use Logger; private $accountNumber; public function __construct($accountNumber) { $this->accountNumber = $accountNumber; $this->log("A new $accountNumber bank account created"); } }

    Code language: PHP (php)8
  • Kedua, tentukan sifat baru yang disebut

    class BankAccount { use Logger; private $accountNumber; public function __construct($accountNumber) { $this->accountNumber = $accountNumber; $this->log("A new $accountNumber bank account created"); } }

    Code language: PHP (php)_9 yang terdiri dari

    class BankAccount { use Logger; private $accountNumber; public function __construct($accountNumber) { $this->accountNumber = $accountNumber; $this->log("A new $accountNumber bank account created"); } }

    Code language: PHP (php)7dan

    class BankAccount { use Logger; private $accountNumber; public function __construct($accountNumber) { $this->accountNumber = $accountNumber; $this->log("A new $accountNumber bank account created"); } }

    Code language: PHP (php)8 sifat. Dalam metode

    class User { use Logger; public function __construct() { $this->log('A new user created'); } }

    Code language: PHP (php)2 dari sifat

    class BankAccount { use Logger; private $accountNumber; public function __construct($accountNumber) { $this->accountNumber = $accountNumber; $this->log("A new $accountNumber bank account created"); } }

    Code language: PHP (php)9, panggil metode 

    class User { use Logger; public function __construct() { $this->log('A new user created'); } }

    Code language: PHP (php)4 dan

    class User { use Logger; public function __construct() { $this->log('A new user created'); } }

    Code language: PHP (php)5 dari sifat

    class BankAccount { use Logger; private $accountNumber; public function __construct($accountNumber) { $this->accountNumber = $accountNumber; $this->log("A new $accountNumber bank account created"); } }

    Code language: PHP (php)7 dan

    class BankAccount { use Logger; private $accountNumber; public function __construct($accountNumber) { $this->accountNumber = $accountNumber; $this->log("A new $accountNumber bank account created"); } }

    Code language: PHP (php)8
  • Ketiga, gunakan sifat

    class BankAccount { use Logger; private $accountNumber; public function __construct($accountNumber) { $this->accountNumber = $accountNumber; $this->log("A new $accountNumber bank account created"); } }

    Code language: PHP (php)9 dalam metode 

    class User { use Logger; public function __construct() { $this->log('A new user created'); } }

    Code language: PHP (php)9 dari kelas

    <?php trait Preprocessor { public function preprocess() { echo 'Preprocess...done' . '<br/>'; } } trait Compiler { public function compile() { echo 'Compile code.. done' . '<br/>'; } } trait Assembler { public function createObjCode() { echo 'Create the object code files.. done.' . '<br/>'; } } trait Linker { public function createExec() { echo 'Create the executable file...done' . '<br/>'; } } class IDE { use Preprocessor, Compiler, Assembler, Linker; public function run() { $this->preprocess(); $this->compile(); $this->createObjCode(); $this->createExec(); echo 'Execute the file...done' . '<br/>'; } } $ide = new IDE(); $ide->run();

    Code language: HTML, XML (xml)0 untuk mensimulasikan penyalinan file

Resolusi konflik metode sifat PHP

Melebihi metode sifat

Ketika sebuah kelas menggunakan banyak ciri yang memiliki nama metode yang sama, PHP akan memunculkan kesalahan fatal.  

Untungnya, Anda dapat menginstruksikan PHP untuk menggunakan metode tersebut dengan menggunakan kata kunci

<?php trait Preprocessor { public function preprocess() { echo 'Preprocess...done' . '<br/>'; } } trait Compiler { public function compile() { echo 'Compile code.. done' . '<br/>'; } } trait Assembler { public function createObjCode() { echo 'Create the object code files.. done.' . '<br/>'; } } trait Linker { public function createExec() { echo 'Create the executable file...done' . '<br/>'; } } class IDE { use Preprocessor, Compiler, Assembler, Linker; public function run() { $this->preprocess(); $this->compile(); $this->createObjCode(); $this->createExec(); echo 'Execute the file...done' . '<br/>'; } } $ide = new IDE(); $ide->run();

Code language: HTML, XML (xml)1. Sebagai contoh

<?php trait FileLogger { public function log($msg) { echo 'File Logger ' . date('Y-m-d h:i:s') . ':' . $msg . '<br/>'; } } trait DatabaseLogger { public function log($msg) { echo 'Database Logger ' . date('Y-m-d h:i:s') . ':' . $msg . '<br/>'; } } class Logger { use FileLogger, DatabaseLogger{ FileLogger::log insteadof DatabaseLogger; } } $logger = new Logger(); $logger->log('this is a test message #1'); $logger->log('this is a test message #2');

Code language: HTML, XML (xml)

Kedua sifat

<?php trait Preprocessor { public function preprocess() { echo 'Preprocess...done' . '<br/>'; } } trait Compiler { public function compile() { echo 'Compile code.. done' . '<br/>'; } } trait Assembler { public function createObjCode() { echo 'Create the object code files.. done.' . '<br/>'; } } trait Linker { public function createExec() { echo 'Create the executable file...done' . '<br/>'; } } class IDE { use Preprocessor, Compiler, Assembler, Linker; public function run() { $this->preprocess(); $this->compile(); $this->createObjCode(); $this->createExec(); echo 'Execute the file...done' . '<br/>'; } } $ide = new IDE(); $ide->run();

Code language: HTML, XML (xml)_2 dan

<?php trait Preprocessor { public function preprocess() { echo 'Preprocess...done' . '<br/>'; } } trait Compiler { public function compile() { echo 'Compile code.. done' . '<br/>'; } } trait Assembler { public function createObjCode() { echo 'Create the object code files.. done.' . '<br/>'; } } trait Linker { public function createExec() { echo 'Create the executable file...done' . '<br/>'; } } class IDE { use Preprocessor, Compiler, Assembler, Linker; public function run() { $this->preprocess(); $this->compile(); $this->createObjCode(); $this->createExec(); echo 'Execute the file...done' . '<br/>'; } } $ide = new IDE(); $ide->run();

Code language: HTML, XML (xml)3 memiliki metode 

<?php trait Preprocessor { public function preprocess() { echo 'Preprocess...done' . '<br/>'; } } trait Compiler { public function compile() { echo 'Compile code.. done' . '<br/>'; } } trait Assembler { public function createObjCode() { echo 'Create the object code files.. done.' . '<br/>'; } } trait Linker { public function createExec() { echo 'Create the executable file...done' . '<br/>'; } } class IDE { use Preprocessor, Compiler, Assembler, Linker; public function run() { $this->preprocess(); $this->compile(); $this->createObjCode(); $this->createExec(); echo 'Execute the file...done' . '<br/>'; } } $ide = new IDE(); $ide->run();

Code language: HTML, XML (xml)4 yang sama

Di kelas Logger , kami menyelesaikan konflik nama metode dengan menetapkan bahwa metode

<?php trait Preprocessor { public function preprocess() { echo 'Preprocess...done' . '<br/>'; } } trait Compiler { public function compile() { echo 'Compile code.. done' . '<br/>'; } } trait Assembler { public function createObjCode() { echo 'Create the object code files.. done.' . '<br/>'; } } trait Linker { public function createExec() { echo 'Create the executable file...done' . '<br/>'; } } class IDE { use Preprocessor, Compiler, Assembler, Linker; public function run() { $this->preprocess(); $this->compile(); $this->createObjCode(); $this->createExec(); echo 'Execute the file...done' . '<br/>'; } } $ide = new IDE(); $ide->run();

Code language: HTML, XML (xml)4 dari sifat

<?php trait Preprocessor { public function preprocess() { echo 'Preprocess...done' . '<br/>'; } } trait Compiler { public function compile() { echo 'Compile code.. done' . '<br/>'; } } trait Assembler { public function createObjCode() { echo 'Create the object code files.. done.' . '<br/>'; } } trait Linker { public function createExec() { echo 'Create the executable file...done' . '<br/>'; } } class IDE { use Preprocessor, Compiler, Assembler, Linker; public function run() { $this->preprocess(); $this->compile(); $this->createObjCode(); $this->createExec(); echo 'Execute the file...done' . '<br/>'; } } $ide = new IDE(); $ide->run();

Code language: HTML, XML (xml)2 akan digunakan sebagai ganti dari sifat

<?php trait Preprocessor { public function preprocess() { echo 'Preprocess...done' . '<br/>'; } } trait Compiler { public function compile() { echo 'Compile code.. done' . '<br/>'; } } trait Assembler { public function createObjCode() { echo 'Create the object code files.. done.' . '<br/>'; } } trait Linker { public function createExec() { echo 'Create the executable file...done' . '<br/>'; } } class IDE { use Preprocessor, Compiler, Assembler, Linker; public function run() { $this->preprocess(); $this->compile(); $this->createObjCode(); $this->createExec(); echo 'Execute the file...done' . '<br/>'; } } $ide = new IDE(); $ide->run();

Code language: HTML, XML (xml)3

Bagaimana jika Anda ingin menggunakan kedua metode

<?php trait Preprocessor { public function preprocess() { echo 'Preprocess...done' . '<br/>'; } } trait Compiler { public function compile() { echo 'Compile code.. done' . '<br/>'; } } trait Assembler { public function createObjCode() { echo 'Create the object code files.. done.' . '<br/>'; } } trait Linker { public function createExec() { echo 'Create the executable file...done' . '<br/>'; } } class IDE { use Preprocessor, Compiler, Assembler, Linker; public function run() { $this->preprocess(); $this->compile(); $this->createObjCode(); $this->createExec(); echo 'Execute the file...done' . '<br/>'; } } $ide = new IDE(); $ide->run();

Code language: HTML, XML (xml)_4 dari sifat

<?php trait Preprocessor { public function preprocess() { echo 'Preprocess...done' . '<br/>'; } } trait Compiler { public function compile() { echo 'Compile code.. done' . '<br/>'; } } trait Assembler { public function createObjCode() { echo 'Create the object code files.. done.' . '<br/>'; } } trait Linker { public function createExec() { echo 'Create the executable file...done' . '<br/>'; } } class IDE { use Preprocessor, Compiler, Assembler, Linker; public function run() { $this->preprocess(); $this->compile(); $this->createObjCode(); $this->createExec(); echo 'Execute the file...done' . '<br/>'; } } $ide = new IDE(); $ide->run();

Code language: HTML, XML (xml)2 dan

<?php trait Preprocessor { public function preprocess() { echo 'Preprocess...done' . '<br/>'; } } trait Compiler { public function compile() { echo 'Compile code.. done' . '<br/>'; } } trait Assembler { public function createObjCode() { echo 'Create the object code files.. done.' . '<br/>'; } } trait Linker { public function createExec() { echo 'Create the executable file...done' . '<br/>'; } } class IDE { use Preprocessor, Compiler, Assembler, Linker; public function run() { $this->preprocess(); $this->compile(); $this->createObjCode(); $this->createExec(); echo 'Execute the file...done' . '<br/>'; } } $ide = new IDE(); $ide->run();

Code language: HTML, XML (xml)3?

Metode sifat aliasing

Dengan menggunakan alias untuk nama metode yang sama dari beberapa sifat, Anda dapat menggunakan kembali semua metode dalam sifat tersebut

Anda menggunakan kata kunci

<?php trait Reader { public function read($source) { echo sprintf('Read from %s <br>', $source); } } trait Writer { public function write($destination) { echo sprintf('Write to %s <br>', $destination); } } trait Copier { use Reader, Writer; public function copy($source, $destination) { $this->read($source); $this->write($destination); } } class FileUtil { use Copier; public function copyFile($source, $destination) { $this->copy($source, $destination); } }

Code language: HTML, XML (xml)_2 untuk alias metode suatu sifat ke nama yang berbeda di dalam kelas yang menggunakan sifat tersebut

Contoh berikut mengilustrasikan bagaimana metode sifat alias untuk menyelesaikan konflik nama metode

class Logger { use FileLogger, DatabaseLogger{ DatabaseLogger::log as logToDatabase; FileLogger::log insteadof DatabaseLogger; } } $logger = new Logger(); $logger->log('this is a test message #1'); $logger->logToDatabase('this is a test message #2');

Code language: PHP (php)

Metode 

<?php trait Preprocessor { public function preprocess() { echo 'Preprocess...done' . '<br/>'; } } trait Compiler { public function compile() { echo 'Compile code.. done' . '<br/>'; } } trait Assembler { public function createObjCode() { echo 'Create the object code files.. done.' . '<br/>'; } } trait Linker { public function createExec() { echo 'Create the executable file...done' . '<br/>'; } } class IDE { use Preprocessor, Compiler, Assembler, Linker; public function run() { $this->preprocess(); $this->compile(); $this->createObjCode(); $this->createExec(); echo 'Execute the file...done' . '<br/>'; } } $ide = new IDE(); $ide->run();

Code language: HTML, XML (xml)4 dari kelas

<?php trait Preprocessor { public function preprocess() { echo 'Preprocess...done' . '<br/>'; } } trait Compiler { public function compile() { echo 'Compile code.. done' . '<br/>'; } } trait Assembler { public function createObjCode() { echo 'Create the object code files.. done.' . '<br/>'; } } trait Linker { public function createExec() { echo 'Create the executable file...done' . '<br/>'; } } class IDE { use Preprocessor, Compiler, Assembler, Linker; public function run() { $this->preprocess(); $this->compile(); $this->createObjCode(); $this->createExec(); echo 'Execute the file...done' . '<br/>'; } } $ide = new IDE(); $ide->run();

Code language: HTML, XML (xml)3 memiliki nama baru (

<?php trait Reader { public function read($source) { echo sprintf('Read from %s <br>', $source); } } trait Writer { public function write($destination) { echo sprintf('Write to %s <br>', $destination); } } trait Copier { use Reader, Writer; public function copy($source, $destination) { $this->read($source); $this->write($destination); } } class FileUtil { use Copier; public function copyFile($source, $destination) { $this->copy($source, $destination); } }

Code language: HTML, XML (xml)5)  dalam konteks kelas Logger

Dalam tutorial ini, Anda telah mempelajari cara menggunakan ciri-ciri PHP untuk menggunakan kembali kode di luar hierarki kelas

Bisakah suatu sifat menggunakan sifat dalam PHP?

Sifat juga bisa menggunakan sifat lain . Dalam hal ini, semua kode dari sifat yang digunakan dimasukkan ke dalam sifat tersebut, dan kemudian ke dalam kelas yang menggunakan sifat tersebut. Sebagai contoh. sifat SayHello { fungsi publik sayHello() { echo 'Halo.

Bisakah kita menggunakan banyak ciri di PHP?

PHP tidak mendukung pewarisan berganda tetapi dengan menggunakan Antarmuka di PHP atau menggunakan Sifat di PHP alih-alih kelas, kita dapat mengimplementasikannya.

Apakah ciri-ciri PHP diwariskan?

Dalam PHP, sifat adalah cara untuk memungkinkan pengembang menggunakan kembali metode kelas independen yang ada dalam hierarki pewarisan yang berbeda. Sederhananya, sifat memungkinkan Anda membuat metode yang diinginkan dalam pengaturan kelas, menggunakan kata kunci sifat. Anda kemudian dapat mewarisi kelas ini melalui kata kunci use .

Bisakah sifat memiliki konstruktor?

Baik sifat dan kelas abstrak menyediakan mekanisme untuk dapat digunakan kembali. Namun, ada beberapa perbedaan mendasar antara keduanya. Kami dapat memperluas dari beberapa ciri, tetapi hanya satu kelas abstrak. Kelas abstrak dapat memiliki parameter konstruktor, sedangkan sifat tidak bisa

Postingan terbaru

LIHAT SEMUA