0

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?

PeeHaa
  • 71,436
  • 58
  • 190
  • 262
user961627
  • 12,379
  • 42
  • 136
  • 210

3 Answers3

3

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

Community
  • 1
  • 1
Colandus
  • 1,634
  • 13
  • 21
  • but is the `Utils::` necessary as a prefix, rather than just `hello()`? Assuming there's no other class required in the file that also has a `hello()` method. – user961627 Mar 20 '13 at 15:05
  • Yes, that's what indicates a static function call. If you just write hello() you are calling a global function not from a class. – Colandus Mar 20 '13 at 15:06
0

actually you call static methods like this:

Utils::hello();
ITroubs
  • 11,094
  • 4
  • 27
  • 25
0

You can call it directly like:

echo Utils::hello();

Here is a PHPFiddle example

Mihai Matei
  • 24,166
  • 5
  • 32
  • 50