在现代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的一些基本概念。通过使用这些概念,你可以编写更易于维护、扩展和重用的代码。