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?

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

2 Comments

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.
Yes, that's what indicates a static function call. If you just write hello() you are calling a global function not from a class.
0

actually you call static methods like this:

Utils::hello();

Comments

0

You can call it directly like:

echo Utils::hello();

Here is a PHPFiddle example

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.