在現代PHP(PHP 5.3及更高版本)中,面向對象編程(OOP)被廣泛應用。以下是一些在現代PHP中使用OOP的常見方法和概念:
class Person {
public $name;
public $age;
public function sayHello() {
echo "Hello, my name is $this->name and I am $this->age years old.";
}
}
$person = new Person();
$person->name = "John";
$person->age = 30;
$person->sayHello(); // 輸出: Hello, my name is John and I am 30 years old.
class Person {
private $name;
private $age;
public function getName() {
return $this->name;
}
public function setName($name) {
$this->name = $name;
}
public function getAge() {
return $this->age;
}
public function setAge($age) {
$this->age = $age;
}
// ...其他方法
}
class Employee extends Person {
private $salary;
public function getSalary() {
return $this->salary;
}
public function setSalary($salary) {
$this->salary = $salary;
}
// ...其他方法
}
interface Speaker {
public function speak();
}
class Person implements Speaker {
// ...其他屬性和方法
public function speak() {
echo "Hello, my name is $this->name.";
}
}
abstract class Animal {
abstract public function makeSound();
// ...其他屬性和方法
}
class Dog extends Animal {
public function makeSound() {
echo "Woof!";
}
// ...其他屬性和方法
}
trait Logger {
public function log($message) {
echo "Log: $message";
}
}
class Person {
use Logger;
// ...其他屬性和方法
}
$person = new Person();
$person->log("Something happened."); // 輸出: Log: Something happened.
這些只是現代PHP中OOP的一些基本概念。通過使用這些概念,你可以編寫更易于維護、擴展和重用的代碼。