Belajar PHP OOP (Object-Oriented Programming) adalah langkah penting untuk menulis kode yang lebih rapi, terstruktur, dan mudah dikembangkan. Berikut adalah penjelasan dasar dan contoh sederhana agar kamu bisa langsung praktik.
π§ Konsep Dasar OOP di PHP
- Class β Cetakan/Blueprint dari objek.
- Object β Hasil instansiasi dari class.
- Property β Variabel dalam class.
- Method β Fungsi dalam class.
- Constructor β Method khusus yang dijalankan saat objek dibuat.
- Encapsulation β Mengontrol akses data (public/private/protected).
- Inheritance β Pewarisan class.
- Polymorphism β Method yang bisa ditimpa (override).
π¦ Contoh Sederhana: Class Mobil
php
Copy
Edit<?php
// Definisi class
class Mobil {
// Properties
public $merk;
public $warna;
// Constructor
public function __construct($merk, $warna) {
$this->merk = $merk;
$this->warna = $warna;
}
// Method
public function jalan() {
return "Mobil $this->merk sedang berjalan.";
}
public function info() {
return "Merk: $this->merk, Warna: $this->warna";
}
}
// Membuat objek
$mobil1 = new Mobil("Toyota", "Merah");
$mobil2 = new Mobil("Honda", "Hitam");
// Mengakses method dan property
echo $mobil1->jalan(); // Output: Mobil Toyota sedang berjalan.
echo "<br>";
echo $mobil2->info(); // Output: Merk: Honda, Warna: Hitam
?>
𧬠Contoh Pewarisan (Inheritance)
php
Copy
Edit<?php
class Kendaraan {
public $merk;
public function __construct($merk) {
$this->merk = $merk;
}
public function suaraMesin() {
return "Brrrrr...";
}
}
// Class Turunan
class Motor extends Kendaraan {
public function jalan() {
return "Motor $this->merk melaju!";
}
}
$motor = new Motor("Yamaha");
echo $motor->jalan(); // Output: Motor Yamaha melaju!
echo "<br>";
echo $motor->suaraMesin(); // Output: Brrrrr...
?>
π Contoh Encapsulation
php
Copy
Edit<?php
class User {
private $password;
public function setPassword($pwd) {
if (strlen($pwd) >= 6) {
$this->password = $pwd;
return "Password disimpan!";
} else {
return "Password terlalu pendek!";
}
}
public function getPassword() {
return str_repeat("*", strlen($this->password));
}
}
$user = new User();
echo $user->setPassword("12345"); // Output: Password terlalu pendek!
echo "<br>";
echo $user->setPassword("rahasia"); // Output: Password disimpan!
echo "<br>";
echo $user->getPassword(); // Output: *******
?>