在 PHP 中,實現數據綁定的一個常用方法是使用對象屬性
class User
{
public $name;
public $email;
public function __construct($name, $email)
{
$this->name = $name;
$this->email = $email;
}
}
class User
{
// ...
public function setName($name)
{
$this->name = $name;
$this->email = substr($name, 0, strpos($name, '@')) . '@example.com';
}
// ...
}
class UserManager
{
private $users = [];
public function addUser(User $user)
{
$this->users[$user->name] = $user;
}
public function getUserByName($name)
{
return isset($this->users[$name]) ? $this->users[$name] : null;
}
}
$userManager = new UserManager();
$user = new User('John Doe', 'john@example.com');
$userManager->addUser($user);
echo $userManager->getUserByName('John Doe')->name . ' - ' . $userManager->getUserByName('John Doe')->email . PHP_EOL;
$userManager->getUserByName('John Doe')->setName('Jane Doe');
echo $userManager->getUserByName('Jane Doe')->name . ' - ' . $userManager->getUserByName('Jane Doe')->email . PHP_EOL;
在這個例子中,我們通過在 User 類中定義 setter 方法實現了數據綁定。當用戶名更改時,電子郵件前綴也會自動更新。通過使用 UserManager 類,我們可以方便地添加、獲取和更新 User 對象及其屬性。