user961627
user961627

Reputation: 12747

php class methods used statically without class reference?

I have a class like this:

class Utils{

   public function hello()
   {
      return "<b>Hello World</b></br>";
   }

}

Can I now do something directly like this in my page.php:

require_once("classes/Utils.php");

echo hello();

Or must I do this:

$u = new Utils;
$u->hello();

even though the function contains no object properties that need to be instantiated?

Upvotes: 0

Views: 68

Answers (3)

N&#228;bil Y
N&#228;bil Y

Reputation: 1650

Yes, if you declare your function as static.

class Utils{

   public static function hello()
   {
      return "<b>Hello World</b></br>";
   }

}

and call it as

Utils::hello()

php static function

Upvotes: 3

Mihai Matei
Mihai Matei

Reputation: 24276

You can call it directly like:

echo Utils::hello();

Here is a PHPFiddle example

Upvotes: 0

ITroubs
ITroubs

Reputation: 11215

actually you call static methods like this:

Utils::hello();

Upvotes: 0

Related Questions