Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiating class method without instantiating the class in PHP no longer possible?

Tags:

methods

php

class

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.

like image 948
richardgirges Avatar asked Jul 14 '12 05:07

richardgirges


People also ask

Can static methods can be called without instantiating the class first?

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.

Which member or method can be accessed without instantiating class?

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.

How can we call a method without creating object 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).


1 Answers

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();
    }
}
like image 160
Lior Cohen Avatar answered Sep 24 '22 05:09

Lior Cohen