在PHP中,我們可以封裝方法(函數)來實現代碼的模塊化和復用。以下是一些常見的PHP封裝方法的方式:
function sayHello() {
echo "Hello, World!";
}
sayHello();
class Person {
public $name;
public function sayHello() {
echo "Hello, my name is " . $this->name;
}
}
$person = new Person();
$person->name = "Alice";
$person->sayHello();
class Math {
public static function add($a, $b) {
return $a + $b;
}
}
echo Math::add(2, 3);
$add = function($a, $b) {
return $a + $b;
};
echo $add(2, 3);
trait Logger {
public function log($message) {
echo "[" . date('Y-m-d H:i:s') . "] " . $message;
}
}
class MyClass {
use Logger;
public function doSomething() {
$this->log("Doing something...");
}
}
$obj = new MyClass();
$obj->doSomething();