Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call static method from instance in PHP, future deprecation?

Tags:

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.

like image 220
Dan Lugg Avatar asked Jun 18 '11 20:06

Dan Lugg


People also ask

Can you call a static method from an instance?

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

Can we inherit static method in PHP?

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 should I use static methods in PHP?

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.

Do static methods return anything?

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.


2 Answers

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.

like image 168
Nicolò Martini Avatar answered Sep 25 '22 03:09

Nicolò Martini


You can always:

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

If you want to be explicit about the method beeing static

like image 39
FrancescoMM Avatar answered Sep 22 '22 03:09

FrancescoMM