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.
Java syntax allows calling static methods from an instance. For example, we could create this code and it would compile and run correctly: public static void main(String args) { Example ex = new Example();
PHP implements a feature called late static bindings which can be used to reference the called class in a context of static inheritance. More precisely, late static bindings work by storing the class named in the last "non-forwarding call".
When to define static methods ? The static keyword is used in the context of variables and methods that are common to all the objects of the class. Therefore, any logic which can be shared among multiple instances of a class should be extracted and put inside the static method.
it is a method accessible from outside the class where it is defined (public), it is a static method (static), it does not return any result (return type is void), and.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With