在 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 对象及其属性。