Typed Properties, Membuat Kode Lebih Rapi di PHP

Typed Properties, Membuat Kode Lebih Rapi di PHP

Typed Properties diperkenalkan di PHP 7.4 untuk meningkatkan kejelasan dan keandalan kode dengan mendefinisikan tipe data untuk properti kelas. Fitur ini membantu mendeteksi kesalahan lebih awal dan membuat kode lebih rapi, mudah dipahami, dan lebih aman.

Apa Itu Typed Properties?

Typed Properties memungkinkan Anda menentukan tipe data yang harus dimiliki oleh properti dalam sebuah kelas. Jika properti diisi dengan tipe data yang tidak sesuai, PHP akan memunculkan error saat runtime.

Keuntungan Menggunakan Typed Properties

  1. Validasi Tipe Otomatis: PHP memvalidasi tipe data sehingga Anda tidak perlu menulis logika tambahan untuk memeriksa tipe data.
  2. Kode Lebih Bersih: Dengan tipe data eksplisit, kode lebih mudah dibaca dan dipahami.
  3. Pengurangan Bug: Typed properties membantu mendeteksi bug lebih awal.
  4. IDE Friendly: IDE dapat memberikan auto-completion dan deteksi error lebih baik.

Contoh Penggunaan Typed Properties

Sebelum PHP 7.4 (Tanpa Typed Properties)

class User {
    private $name;
    private $age;

    public function setName(string $name) {
        $this->name = $name;
    }

    public function setAge(int $age) {
        $this->age = $age;
    }

    public function getName(): string {
        return $this->name;
    }

    public function getAge(): int {
        return $this->age;
    }
}

$user = new User();
$user->setName("John");
$user->setAge(30);
echo $user->getName(); // John
PHP

Setelah PHP 7.4 (Dengan Typed Properties)

class User {
    public string $name;
    public int $age;
}

$user = new User();
$user->name = "John";
$user->age = 30;

echo $user->name; // John
echo $user->age;  // 30
PHP

Penjelasan:

  • Tidak perlu setter dan getter jika tidak ada logika tambahan.
  • Properti langsung didefinisikan dengan tipe datanya.

Tipe Data yang Didukung

  1. Skalar: int, float, string, bool.
  2. Tipe Kompleks: array, object, iterable, callable.
  3. Tipe Khusus: self, parent, ? (nullable).
  4. Class Type: Dapat menggunakan nama kelas sebagai tipe data.

Contoh Tipe Data Kompleks

class Product {
    public string $name;
    public ?float $price; // Nullable float
}

$product = new Product();
$product->name = "Laptop";
$product->price = null; // Nilai null diperbolehkan
PHP

Handling Error pada Typed Properties

PHP akan menghasilkan error jika tipe data tidak sesuai.

Contoh

class Order {
    public int $quantity;
}

$order = new Order();
$order->quantity = "10"; // Error: TypeError
PHP

Error:

Fatal error: Uncaught TypeError: Typed property Order::$quantity must be int
PHP

Default Value pada Typed Properties

Typed Properties mendukung nilai default:

class Config {
    public int $timeout = 30; // Default value
}
PHP

Nullable Typed Properties

Tambahkan tanda ? untuk properti yang bisa memiliki nilai null:

class Customer {
    public ?string $email; // Bisa null
}

$customer = new Customer();
$customer->email = null; // Tidak error
PHP

Typed Properties pada Dependency Injection

Typed Properties juga mempermudah dependency injection:

class Logger {
    public function log(string $message) {
        echo $message;
    }
}

class App {
    public Logger $logger;

    public function __construct(Logger $logger) {
        $this->logger = $logger;
    }
}

$logger = new Logger();
$app = new App($logger);
$app->logger->log("Application started."); // Application started.
PHP

Kesimpulan

Typed Properties:

  • Membuat kode lebih rapi dan mudah dipahami.
  • Mengurangi kemungkinan bug dengan validasi tipe otomatis.
  • Sangat berguna untuk aplikasi besar dengan banyak kelas dan properti.

Typed Properties adalah salah satu fitur modern PHP yang mengarah ke praktik penulisan kode yang lebih baik dan lebih terstruktur. Jika Anda belum menggunakannya, mulai sekarang untuk meningkatkan kualitas kode Anda! 🚀

Leave a Reply

Your email address will not be published. Required fields are marked *