如何在PHPDoc中弃用PHP的魔术属性?

问题描述 投票:15回答:3

有没有办法将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)并且感觉不太优雅。

php phpdoc
3个回答
3
投票

@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;

截图:

PhpStorm Screenshot


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);
        }
        // ...
    }
}

-1
投票

我认为你最好的选择是明确定义$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
    } 
}
© www.soinside.com 2019 - 2024. All rights reserved.