有没有办法将magic property标记为已弃用?考虑以下简化代码:
/**
* 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
}
}
}
但是这两个都破坏了我的代码(没有调用getter)并且感觉不太优雅。
@mixin方法至少适用于PhpStorm:
/**
* class or trait for the {@mixin} annotation
*/
trait DeprecatedExampleTrait {
/**
* Declare it as private to increase the warning level
* @deprecated
* @var string
*/
public $foo;
}
/**
* Example class
*
* @mixin DeprecatedExampleTrait
*
* @property string $newFoo A foo variable.
*/
class Example {
/**
* Magic getter
*/
public function __get($var) {
if (in_array($var, ['foo', 'newFoo'])) {
// do & return something
}
}
}
$example = new Example;
$example->foo;
截图:
这对于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);
}
// ...
}
}
我认为你最好的选择是明确定义$foo
属性,以便你可以用@deprecated
记录它。为了保持当前使用// do & return something
产生的$myExample->foo
行为,您可以在构造函数中为$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
}
}