在 PHP 中从实例调用静态方法,将来会弃用吗?

问题描述 投票:0回答:2

虽然我知道当在静态上下文中调用方法时

$this
变量不可用,但为了帮助将我的应用程序组件彼此分离,我认为从实例调用静态方法是有意义的。例如:

class MyExample{
    private static $_data = array();
    public static function setData($key, $value){
        self::$_data[$key] = $value;
    }
    // other non-static methods, using self::$_data
}

// to decouple, another class or something has been passed an instance of MyExample
// rather than calling MyExample::setData() explicitly
// however, this data is now accessible by other instances
$example->setData('some', 'data');

是否有弃用此类功能的计划,或者我是否可以期待对这种功能的支持?我与

error_reporting(-1)
一起工作以确保非常严格的开发环境,目前还没有任何问题(PHP 5.3.6)但是我知道反向变得不受支持;也就是说,实例方法被静态调用。

php this static-methods deprecated instance-methods
2个回答
41
投票

来自Php文档

声明为静态的属性不能用实例化访问 类对象(虽然静态方法可以)。

所以我觉得会前向支持很长一段时间


3
投票

您可以随时使用:

$class = get_class($example);
$class::setData('some', 'data');

如果您想明确说明该方法是静态的。

或者,在类内部,您也可以在非静态方法中使用关键字 self 和 static(以及函数 get_called_class):

self::setData('some', 'data');

static::setData('some', 'data');

$class = get_called_class();
$class::setData('some', 'data');
  • Self 引用声明方法的类:如果该方法在 Animal 类中并且 Parrot extends Animal,即使在 Parrot 类型的对象中调用,self 也会引用 Animal 类。

  • Static 引用正在使用的对象的类($this 的类),因此如果该方法在 Animal 中并且它在 Parrot 的实例上调用它引用类 Parrot(如 get_class 和 get_called_class 函数)

所以,如果您在扩展 Animal 的对象 Parrot 中,并且以下代码是在类 Animal 中编写的:

self::setData('some', 'data');

就像

Animal::setData('some', 'data');

static::setData('some', 'data');

就像

Parrot::setData('some', 'data');

作为一个建议,我宁愿创建一个具有信息名称的非静态方法来调用静态方法,而不是每次都从外部获取类。在我看来更简洁、干净和清晰:

public function setStaticData($a,$b) {
    return static::setData($a,$b);
}
© www.soinside.com 2019 - 2024. All rights reserved.