开发者

Call static method from instance in PHP, future deprecation?

开发者 https://www.devze.com 2023-03-14 01:53 出处:网络
While I understand the $this variable is not available when a method is called in a static context, to assist in decoupling my application components from one-another I figured it would开发者_如何学编

While I understand the $this variable is not available when a method is called in a static context, to assist in decoupling my application components from one-another I figured it would开发者_如何学编程 make sense to call static methods from an instance. For example:

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');

Are there plans to deprecate this sort of functionality, or am I right to expect support for this going forward? I work with error_reporting(-1) to ensure a very strict development environment, and there aren't any issues as of yet (PHP 5.3.6) however I am aware of the reverse becoming unsupported; that is, instance methods being called statically.


From the Php documentation:

A property declared as static can not be accessed with an instantiated class object (though a static method can).

So I think it will be forward-supported for a long time.


You can always:

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

If you want to be explicit about the method beeing static

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号