。public
protected
private
public
成员(属性和方法)声明为public
protected
:> protected
成员声明为private
:private
成员声明为>的成员可被访问从定义的类中的类中。这提供了最强的封装级别,限制了对类的内部工作的访问。
<code class="php"><?php class User { private $name; private $email; public function __construct($name, $email) { $this->name = $name; $this->email = $email; } public function getName() { return $this->name; } public function getEmail() { return $this->email; } public function setEmail($email) { // Add validation here if needed $this->email = $email; } } $user = new User("John Doe", "john.doe@example.com"); echo $user->getName(); // Accessing name through a public getter method echo $user->getEmail(); // Accessing email through a public getter method $user->setEmail("john.updated@example.com"); // Updating email through a public setter method //echo $user->name; // This would throw an error because $name is private. ?></code>
在PHP 7中实现封装,您可以使用适当的访问修饰符声明类属性和方法。 例如:在此示例中,$name
$email
getName()
是私有的,这意味着它们只能通过public setEmail()
和
可维护性:
封装的类更容易测试,因为他们的行为通过其公共界面很好地定义了。您可以独立测试每个类,而无需知道内部实现详细信息。
安全:BankAccount
class class封装
<code class="php"><?php class User { private $name; private $email; public function __construct($name, $email) { $this->name = $name; $this->email = $email; } public function getName() { return $this->name; } public function getEmail() { return $this->email; } public function setEmail($email) { // Add validation here if needed $this->email = $email; } } $user = new User("John Doe", "john.doe@example.com"); echo $user->getName(); // Accessing name through a public getter method echo $user->getEmail(); // Accessing email through a public getter method $user->setEmail("john.updated@example.com"); // Updating email through a public setter method //echo $user->name; // This would throw an error because $name is private. ?></code>。 可以直接访问这些属性。
>和BankAccount
方法处理accountNumber
以上是什么是封装,如何在PHP 7中实施它?的详细内容。更多信息请关注PHP中文网其他相关文章!