。 public
protected
private
public
成員(屬性和方法)聲明為public
protected
:> protected
成員聲明為private
:private
成員聲明為>的成員可被訪問從定義的類中的類中。這提供了最強的封裝級別,限制了對類的內部工作的訪問。
<?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. ?>
在PHP 7中實現封裝,您可以使用適當的訪問修飾符聲明類屬性和方法。 例如:在此示例中,$name
$email
getName()
是私有的,這意味著它們只能通過public setEmail()
和
可維護性:
封裝的類更容易測試,因為他們的行為通過其公共界面很好地定義了。您可以獨立測試每個類,而無需知道內部實現詳細信息。
<🎜><🎜><🎜>安全:<🎜> <🎜> <🎜>BankAccount
class class封裝
<?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. ?>
>和BankAccount
方法處理accountNumber
以上是什麼是封裝,如何在PHP 7中實施它?的詳細內容。更多資訊請關注PHP中文網其他相關文章!