0

I've just started using PHP and I've been stuck on this for hours, and yet it seems like a very simple problem. I have a class full of functions and I want to call them, but nothing works. I'll just post a brief *snippet to show the issue:

<?php
class test
{
function writeMsg() {
  Echo "Hello world!";
  }
writeMsg(); 
}
writeMsg(); 
?>

I get the error:

Parse error: syntax error, unexpected 'writeMsg' (T_STRING), expecting function (T_FUNCTION) or const (T_CONST) in /Users/redacted/Sites/projects_PHP7.1/index.php on line 7.

If i delete that call on line 7 and try run again with one in line 9 the error is: Fatal error: Uncaught Error: Call to undefined function writeMsg() in /Users/redacted/Sites/projects_PHP7.1/index.php:9 Stack trace: #0 {main} thrown in /Users/redacted/Sites/projects_PHP7.1/index.php on line 9

I have no idea why any of these errors happen and any help would be greatly appreciated. I just want to be able to call the functions:-( Thank you!

John Conde
  • 217,595
  • 99
  • 455
  • 496
  • You can't execute functions inside of a class like that. You need to instantiate an object from that class and then call that method. – John Conde May 12 '20 at 19:29
  • Thanks for your quick reply. I don't quite speak the lingo yet, could you give me an example of how that is done? thank you – MelancholicTurnip May 12 '20 at 20:30
  • In `index.php` you can do `$test = new test();` (instantiation i.e. create an object from a class) and then `$test->writeMsg();` (call a method within the instance). – halfer May 19 '20 at 17:19
  • You are probably trying to run before you can walk. I would encourage you to find and work through several tutorials - how to use a programming language is too broad for a Q&A site. – halfer May 19 '20 at 17:20

0 Answers0