I'm not sure if I'm losing it or what. I recently jumped back into PHP after a much needed break, and I'm trying to do something that I've always been able to do: call a public class method without instantiating the class. Example:
class Utils
{
public function getTime()
{
return time();
}
}
$time = Utils::getTime();
echo $time;
I used to do this all the time (about two or three years ago), but after hopping into PHP 5.3 on a new sandbox environment that I set up, I keep getting
Fatal error: Call to undefined function getTime() in /mnt/richard/index.php on line 24
Am I missing something silly here? Or is the use of public class methods without class instantiation a now deprecated feature in PHP? Oh how times have changed...
My overall goal is to be able to create methods that belong to a grouped set of classes that can be called in the global scope within other methods and classes. Any help will be much appreciated. Thanks.
In the same way that a static variable is associated with the class as a whole, so is a static method. In the same way that a static variable exists before an object of the class is instantiated, a static method can be called before instantiating an object.
The static member is callable on a class even when no instance of the class has been created. The static member is always accessed by the class name, not the instance name. Only one copy of a static member exists, regardless of how many instances of the class are created.
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).
You shouldn't be calling instance methods as static ones on a class, even if PHP allows you to do so. When invoking:
Utils::getTime();
you are calling an instance method from a static context. You should define getTime
like this instead:
class Utils
{
public static function getTime()
{
// You can't use $this in here. This is a static function. No instance exists.
return time();
}
}
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