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