在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();