Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In PHP, is it a problem to call a static class function using the -> dereferencer

I am using PHP 5.2

I have the following code:

class MyClass {
    public function __construct() {}

    public static function stuff() {
        echo 'This is static! <br />';
    }

}

$myClass = new MyClass();

MyClass::stuff(); // Reference by class.

$myClass->stuff(); // Reference by instance of class.

The output works in both cases here is the output:

This is static!

This is static!

Is there a problem using the 2nd way of referencing versus the 1st?

Since I am not allowed to have a non-static function with the same signature as the static one above that won't be an issue. I want the function to be static because there is also a speed boost when using static functions.

Am I missing anything or is the only issue here regarding the semantics of how the -> dereference syntax does not indicate this is a static function?

like image 546
Tonto McGee Avatar asked Nov 24 '10 20:11

Tonto McGee


People also ask

How can I call static method from static method in PHP?

Example Explained Here, we declare a static method: welcome(). Then, we call the static method by using the class name, double colon (::), and the method name (without creating an instance of the class first).

How static method is invoked in PHP?

To add a static method to the class, static keyword is used. They can be invoked directly outside the class by using scope resolution operator (::) as follows: MyClass::test();

Can we override static method in PHP?

Here comes the call of static method with static keyword. In case there is no overridden function then it will call the function within the class as self keyword does. If the function is overridden then the static keyword will call the overridden function in the derived class.

Can static method be private PHP?

If you need your method to access instance variables, then it is not a static method, whether or not it is private . If it is only for working on non-instance data, then it can be static . Private or public is a completely separate issue.


1 Answers

The docs explicitly say it's okay:

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

However, it's clearer to use ::. I also question the idea that the static method is significantly faster, particularly when no instance fields are used. You should do profiling before you start altering the semantics of your application for performance.

like image 157
Matthew Flaschen Avatar answered Oct 16 '22 15:10

Matthew Flaschen