20

I am getting this error in this PHP code on line 3, what could be wrong? This code has been taken from php manual user notes by frank at interactinet dot com

<?php

public function myMethod()
{
return 'test';
}

public function myOtherMethod()
{
return null;
}

if($val = $this->myMethod())
{
 // $val might be 1 instead of the expected 'test'
}

if( ($val = $this->myMethod()) )
{
// now $val should be 'test'
}

// or to check for false
if( !($val = $this->myMethod()) )
{
// this will not run since $val = 'test' and equates to true
}

// this is an easy way to assign default value only if a value is not returned:

if( !($val = $this->myOtherMethod()) )
{
$val = 'default'
}

?> 
ceejayoz
  • 176,543
  • 40
  • 303
  • 368
Ashish Yadav
  • 253
  • 1
  • 3
  • 7
  • 1
    Looks like this is supposed to be **part of a class definition**. This won't run as is. – deceze Nov 12 '12 at 09:44
  • in addition, the code is showcasing *bad programming*, something you should not do. Why would you want to use the code? – eis Nov 12 '12 at 09:49

2 Answers2

54

The public keyword is used only when declaring a class method.

Since you're declaring a simple function and not a class you need to remove public from your code.

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
DiverseAndRemote.com
  • 19,314
  • 10
  • 61
  • 70
  • 2
    what's the difference between a public function in a class and a function out in the open? – expiredninja Jan 03 '14 at 18:01
  • 9
    You can also hit this error from not closing a bracket & that runs into the next function... It will throw this error on that function. That's what I did. Don't be like me. – Tanner_Gram Nov 02 '18 at 15:19
  • @Tanner_Gram I did what you did so I checked every single braces, and it works – Blues Clues Dec 16 '20 at 04:59
3

You can remove public keyword from your functions, because, you have to define a class in order to declare public, private or protected function