1. 程式人生 > >php魔術方法: __get() 和 __set()的妙用

php魔術方法: __get() 和 __set()的妙用

<?php
class Post {
  private $title;
  private $content;
  private $author;
  private $comments;

  private $_getters = array('title', 'content', 'author', 'comments');
  private $_setters = array('title', 'content', 'author');
  
  public function __get($property) {
    if (in_array($property, $this->_setters)) {
      return $this->$property;
    }
    else if (method_exists($this, '_get_' . $property))
      return call_user_func(array($this, '_get_' . $property));
    else if (in_array($property, $this->_getters) OR method_exists($this, '_set_' . $property))
      throw new Exception('Property "' . $property . '" is write-only.');
    else
      throw new Exception('Property "' . $property . '" is not accessible.');
  }

  public function __set($property, $value) {
    if (in_array($property, $this->_getters)) {
      $this->$property = $value;
    }
    else if (method_exists($this, '_set_' . $property))
      call_user_func(array($this, '_set_' . $property), $value);
    else if (in_array($property, $this->_setters) OR method_exists($this, '_get_' . $property))
      throw new Exception('Property "' . $property . '" is read-only.');
    else
      throw new Exception('Property "' . $property . '" is not accessible.');
  }
}
?>

This way the variables in the $_getters array can be read from the outside and the variables in the $_setters array can be modified from the outside, like this:

<?php
$post = new Post();
$post->title = 'Hello, World';
echo $post->title;

// The following will throw an exception since $comments is read-only:
$post->comments = 23;
?>

And in case you need a less generic getter or setter at some point, you can remove the variable from the $_getters or $_setters array and implement a method like:

<?php
private function _set_title($value) {
  $this->title = str_replace('World', 'Universe', $value);
}
?>

And from the outside the property could still be used with:

<?php
$post->title = 'Hello, World!';
?>

 上面是手冊裡的例子,但是我覺得應該是先判斷類裡面是否有處理屬性的方法,有的話就呼叫該方法,沒有就直接設定該屬性。

相關推薦

php魔術方法 __get() __set()的

<?php class Post { private $title; private $content; private $author; private $comments; private $_getters = array('title',

PHP魔術方法__get__set的用法

PHP中,魔術方法有很多種,本文章給大家記錄分享:__get\__set的用法跟理解 首先,我們得明白oop中的三個訪問修飾符:public、protected、private 分別的意思: 1、公共的,任何地方都可以訪問,包括本類,子類,外部 2、受保護的成員屬性或者方法,只能

PHP魔術方法__get()__set()用法

<?php class person { private $name; function __set($_name, $_value) { $this->$_name = 'set-' . $_value; }

PHP 魔術方法__set() __get() 方法

先看看官方文件的解釋 __set() is run when writing data to inaccessible properties. __get() is utilized for reading data from inaccessible pro

面向物件之魔術方法__get()__set()

__get()方法:這個方法用來獲取私有成員和保護成員屬性值的,有一個引數,引數傳入你要獲取的成員屬性的名稱,返回獲取的屬性值,這個方法不用我們手工的去呼叫,因為我們也可以把這個方法做成私有的方法,是在直接獲取私有屬性的時候物件自動呼叫的。因為私有屬性已經被封裝

魔術方法__set__get

<?php class A{ //用__set、__get魔術方法,欄位必須為私有屬性 private $name = "herghost"; public functio

php 魔術方法魔術常量

ted 簡單 ech auto trait space esp wak 聲明 魔術方法:PHP把類中所有以__(兩個下劃線)開頭的方法當成魔術方法,一般建議用戶不要將自定義的方法前面加上__作為前綴。魔術方法:1. __construct()類的默認構造方法,如果__con

潭州課堂25班Ph201805201 第十一課 繼承,多繼承魔術方法,屬性方法 (課堂筆記)

筆記 父類 當前 TE -s __del__ color true ont 繼承: class p : cls_name = ‘p‘ def __init__(self): print(‘正在實例化‘) def __del__(se

PHP魔術方法魔術常量介紹及使用

有些東西如果不是經常使用,很容易忘記,比如魔術方法和魔術常量。 魔術方法(Magic methods) PHP中把以兩個下劃線__開頭的方法稱為魔術方法,這些方法在PHP中充當了舉足輕重的作用。 魔術方法包括: __construct(),類的建構函式__destruct(),類的解構函式__call(),

PHP 魔術方法

log des ons 函數 私有 func 面向對象編程 自動 pan 一、php中的魔術方法   php在面向對象編程時有一些特殊的方法,會在特定的時機自動調用,我們將這類方法稱為魔術方法。 二、常見的魔術方法及功能   1.構造函數 __construct():當類被

php魔術方法

變量名 數據庫 似的 發生 並且 wakeup fat php魔術方法 ble PHP中的魔術方法總結 :__construct, __destruct , __call, __callStatic,__get, __set, __isset, __unset , __sl

php--魔術方法

克隆 amp 作用 href ted 指定 stat 實現 判斷 在 PHP 中以兩個下劃線開頭的方法,__construct(), __destruct (), __call(), __callStatic(),__get(), __set(), __isset(), _

javastruts框架2(方法的動態靜態調

sof crud turn itl title 得到 tps font star 1.方法的靜態和動態調用:     struts.xml: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts

PHP魔術方法之__call與__callStatic方法

ring 魔術方法 local csdn boa -c isset sta 自動調用 [php] view plain copy <?php class human{ private function t(){ } /

php魔術方法__tostring的應用

www. lstat color 匿名類 http ESS build convert ror 當echo一個對象的時候,會報錯誤 Object of class Person could not be converted to string 我們可以通過魔術方

PHP魔術方法大全

十六 加載 魔術 iss 類的成員 auto head UC AD 十六個魔術方法詳解如下 說明:PHP中把以兩個下劃線__開頭的方法稱為魔術方法(Magic methods),這些方法在PHP中充當了舉足輕重的作用。 魔術方法包括: __construct(),類

PHP魔術方法__call

__call成員方法不存在時候自動調用的魔術方法,php不支持多態,可以通過call實現偽多態。 <?class a{function show(){echo 1;}function call($f,$args){echo "__CALL";}}$obj= new a;$obj-&g

【python041--構造方法構造析造】

判斷 劃線 for 超出 默認 需要 clas 功能 erro 一、魔法方法 1、魔法方法總是被雙下劃線包圍,例如:__init__ 2、為什麽在類實例化的時候,有時候需要構造__init__,有時候不需要呢 舉例說明: #定義一個矩形的類,需要長和寬兩個參數,計算矩形的

PHP魔術方法例項

PHP中把以兩個下劃線__開頭的方法稱為魔術方法,這些方法在PHP中充當了舉足輕重的作用。 魔術方法包括: __construct(),類的建構函式 __destruct(),類的解構函式 __call(),在物件中呼叫一個不可訪問方法時呼叫 __callStatic(),

http請求方法GETPOST 的區別

  GET方式:將表單內容經過編碼之後 ,通過URL傳送, 使用get方式傳送時有255個字元的限制。 POST方式:將表單的內容通過http傳送,post沒有字元長度的限制 使用GET和POST方式傳遞引數 在URL地址後面可以附加一些引數 舉例:h