Tutorial PHP #21: Constructor, Destructor, dan Property

1. Constructor

Constructor adalah method khusus __construct() yang otomatis dijalankan saat object dibuat. Berguna untuk inisialisasi nilai awal property.

<?php
class User {
    public string $nama;
    public string $email;
    public string $role;

    // Constructor dipanggil otomatis saat: $user = new User("Ariq", "ariq@mail.com")
    public function __construct(string $nama, string $email, string $role = "user") {
        $this->nama  = $nama;
        $this->email = $email;
        $this->role  = $role;
        
        echo "Object User '$nama' berhasil dibuat <br>";
    }

    public function info(): string {
        return "{$this->nama} ({$this->email}) - {$this->role}";
    }
}

$user1 = new User("Ariq", "ariq@mail.com", "admin");
// Output: Object User 'Ariq' berhasil dibuat

$user2 = new User("Budi", "budi@mail.com");
// Output: Object User 'Budi' berhasil dibuat
// role default = "user"

echo $user1->info();   // Output: Ariq (ariq@mail.com) - admin
echo $user2->info();   // Output: Budi (budi@mail.com) - user
?>

2. Constructor Promotion (PHP 8+)

PHP 8 memperkenalkan sintaks lebih singkat - deklarasi property sekaligus bisa dilakukan langsung di constructor:

<?php
class Produk {
    // Property langsung dideklarasikan di parameter constructor
    public function __construct(
        public string $nama,
        public float $harga,
        public int $stok = 0
    ) {
        // Tidak perlu $this->nama = $nama dll
    }

    public function totalNilai(): float {
        return $this->harga * $this->stok;
    }
}

$laptop = new Produk("Laptop Asus", 12000000, 5);
echo $laptop->nama;           // Output: Laptop Asus
echo $laptop->totalNilai();   // Output: 60000000
?>

3. Destructor

Destructor adalah method __destruct() yang otomatis dipanggil saat object dihancurkan - biasanya di akhir script atau saat unset().

<?php
class DatabaseConnection {
    private $conn;

    public function __construct(string $dbName) {
        echo "Koneksi ke database $dbName dibuka <br>";
        // $this->conn = new PDO(...)
    }

    public function __destruct() {
        echo "Koneksi database ditutup <br>";
        // Tutup koneksi, bebaskan resource
    }
}

$db = new DatabaseConnection("db_belajar");
// Output: Koneksi ke database db_belajar dibuka

echo "Menjalankan query... <br>";

// Object $db dihancurkan di akhir script
// Output: Koneksi database ditutup
?>

4. Property dengan Getter dan Setter

Best practice OOP: gunakan private/protected untuk property, lalu sediakan getter dan setter untuk mengaksesnya.

<?php
class BankAccount {
    private float $saldo;
    private string $pemilik;

    public function __construct(string $pemilik, float $saldoAwal = 0) {
        $this->pemilik = $pemilik;
        $this->saldo   = $saldoAwal;
    }

    // Getter
    public function getSaldo(): float {
        return $this->saldo;
    }

    public function getPemilik(): string {
        return $this->pemilik;
    }

    // Setter dengan validasi
    public function setor(float $jumlah): void {
        if ($jumlah <= 0) {
            throw new InvalidArgumentException("Jumlah setor harus positif");
        }
        $this->saldo += $jumlah;
    }

    public function tarik(float $jumlah): void {
        if ($jumlah > $this->saldo) {
            throw new RuntimeException("Saldo tidak mencukupi");
        }
        $this->saldo -= $jumlah;
    }
}

$akun = new BankAccount("Ariq", 1000000);
$akun->setor(500000);
echo $akun->getSaldo();    // Output: 1500000

$akun->tarik(200000);
echo $akun->getSaldo();    // Output: 1300000
?>

5. Ringkasan

  • __construct() otomatis dipanggil saat object dibuat - untuk inisialisasi
  • Constructor promotion (PHP 8+) menyederhanakan deklarasi property
  • __destruct() otomatis dipanggil saat object dihancurkan - untuk cleanup
  • Gunakan getter/setter untuk mengontrol akses ke private property

Tutorial berikutnya membahas inheritance, encapsulation, dan polymorphism.