[英]PHP __get __set methods
class Dog {
protected $bark = 'woof!';
public function __get($key) {
if (isset($this->$key)) {
return $this->$key;
}
}
public function __set($key, $val) {
if (isset($this->$key)) {
$this->$key = $val;
}
}
}
使用這些功能有什么意義。
如果我可以使用
$dog = new Dog();
$dog->bark = 'woofy';
echo $dog->bark;
為什么我會費心將“樹皮”聲明為protected
? 在這種情況下,__ __get()
和__set()
方法是否有效地公開了“吠叫”?
在這種情況下,它們確實使$this->bark
有效地公開,因為它們只是直接設置和檢索值。 但是,通過使用 getter 方法,您可以在設置時執行更多工作,例如驗證其內容或修改 class 的其他內部屬性。
不一定必須與對象的屬性一起使用。
這就是使他們強大的原因。
class View extends Framework {
public function __get($key) {
if (array_key_exists($key, $this->registry)) {
return trim($this->registry[$key]);
}
}
}
基本上,我試圖證明它們不必用作 object 屬性的 getter 和 setter。
您通常不會完全按照您離開的方式離開那些__get
和__set
。
這些方法可能有用的方法有很多。 以下是您可以使用這些方法執行的幾個示例。
您可以將屬性設為只讀:
protected $bark = 'woof!';
protected $foo = 'bar';
public function __get($key) {
if (isset($this->$key)) {
return $this->$key;
}
}
public function __set($key, $val) {
if ($key=="foo") {
$this->$key = $val; //bark cannot be changed from outside the class
}
}
您可以在實際獲取或設置數據之前對您擁有的數據進行處理:
// ...
public $timestamp;
public function __set($var, $val)
{
if($var == "date")
{
$this->timestamp = strtotime($val);
}
}
public function __get($var)
{
if($var == date)
{
return date("jS F Y", $this->timestamp);
}
}
使用__set
可以做的另一個簡單示例可能是更新數據庫中的一行。 因此,您要更改的內容不一定在 class 內部,而是使用 class 來簡化更改/接收的方式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.