2016-05-31 61 views
10

有沒有辦法將magic property標記爲已棄用?考慮下面,簡化代碼:如何在PHPDoc中棄用PHP的魔術屬性?

/** 
* Example class 
* 
* @property string $foo A foo variable. 
*/ 
class Example { 
    /** 
    * Magic getter 
    */ 
    public function __get($var) { 
     if('foo' === $var) { 
      // do & return something 
     } 
    } 
} 

現在,如何指示其他開發人員,他們不應該用Example::$foo了嗎?這使我想到的唯一的工作解決方法是:

/** 
* Example class 
*/ 
class Example { 
    /** 
    * A foo variable. 
    * 
    * @var string 
    * @deprecated 
    */ 
    public $foo; 

    /** 
    * Magic getter 
    */ 
    public function __get($var) { 
     if('foo' === $var) { 
      // do & return something 
     } 
    } 
} 

但這兩者打破我的代碼(吸氣不叫),並不會覺得很優雅。

+0

拋出一個警告或異常,並記錄它? –

+0

[看起來合法](https://manual.phpdoc.org/HTMLSmartyConverter/HandS/phpDocumentor/tutorial_tags.deprecated.pkg.html) - 不能編譯? –

+0

@self我不想破壞舊的依賴關係 - 只是指出它不應該用在新的代碼中。 – pamelus

回答

7

這對於PHPDoc來說是不可能的,因爲@deprecated只能與結構元素(documentation)關聯。

如果真的是重要的開發人員知道,他們不應該再使用這個魔法屬性,可以觸發一個E_USER_DEPRECATED錯誤:

/** 
* Example class 
* 
* @property string $foo A foo variable. 
*/ 
class Example { 

    public function __get($name) 
    { 
     if ($name === 'foo') { 
      trigger_error('Property $foo is deprecated and should no longer be used', E_USER_DEPRECATED); 
     } 
     // ... 
    } 
} 
+0

屬性[是一個結構性元素](https://phpdoc.org/docs/latest/glossary.html#term-structural-elements)。 –

+1

是的,但這裏的問題是,如果您可以將'@ deprecated'與'@ property'關聯起來,這是不可能的,因爲您只能將'@ deprecated'與* real *屬性/類/接口/方法聯繫起來 – Pieter

+0

是的,但你的例子並不符合這個問題。在這個問題中,它是一個* real *屬性 –

0

我覺得這裏你最好的選擇將是顯式定義$foo財產,以便您可以用@deprecated對其進行記錄。爲了保持當前使用$myExample->foo所導致的// do & return something行爲,您可以在構造函數中將一個匿名函數分配給$this->foo。因此,該邏輯不再存在於__get()中,只要$foo被明確定義,該邏輯就落在執行路徑之外。

/** 
* Example class 
*/ 
class Example { 

    /** 
    * A foo variable. 
    * 
    * @var string 
    * @deprecated 
    */ 
    public $foo; 

    /** 
    * constructor 
    */ 
    public function __construct() { 
     $this->foo = function() { 
      // do & return something 
     }; 
    } 

    /** 
    * Magic getter 
    */ 
    public function __get($var) { 
     // no longer handles calls to $this->foo 
    } 
} 
+0

將一個匿名函數賦值給'$ this-> foo'不會使這個函數充當getter。訪問'foo'只會返回函數而不是函數的返回值。 –