Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deprecate PHP's magic property in PHPDoc?

Tags:

php

phpdoc

Is there any way to mark a magic property as deprecated? Consider following, simplified code:

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

Now, how to indicate other developers, that they should not use Example::$foo anymore? The only working solution that comes to my mind is:

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

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

But this both breaks my code (getter is not called) and doesn't feel very elegant.

like image 413
pamelus Avatar asked May 31 '16 19:05

pamelus


2 Answers

The @mixin approach works at least with 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;

Screenshot:

PhpStorm Screenshot

like image 83
kaluzki Avatar answered Nov 12 '22 15:11

kaluzki


This is not possible with PHPDoc as the @deprecated can only be associated with structural elements (documentation).

If it is really important for developers to know that they should no longer use this magic property, you could trigger an E_USER_DEPRECATED error:

/**
 * 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);
        }
        // ...
    }
}
like image 43
Pieter Avatar answered Nov 12 '22 14:11

Pieter