1

I thought that the use of the static keyword in the declaration of a class function meant that you could call the function without an instance of the class using the scope resolution operator (::).

For example:

class Foo
{
    public static function static_function() {
        return 'x';
    }
    public function non_static_function() {
        return 'y';
    }
}

// to call static_function:
echo Foo::static_function();

// to call non_static_function:
$foo = new Foo();
echo $foo->non_static_function();

The PHP.net documentation on static seems to support this idea.

I came across some code yesterday that someone had wrote accessing class functions using the scope resolution operator that had NOT been defined with the static keyword. I was surprised and confused to see this worked.

Given my class defined above, Foo, it turns out you can actually do:

echo Foo::static_function();
echo Foo::non_static_function();

Resulting in output xy without generating any errors or warnings.

If you can access non-static class functions without the static keyword, what is the point in it?

Mitch Satchwell
  • 4,770
  • 2
  • 24
  • 31
  • 2
    From the [manual](http://php.net/manual/en/language.oop5.static.php) "Calling non-static methods statically generates an E_STRICT level warning." – naththedeveloper Mar 11 '14 at 10:12
  • duplicate : http://stackoverflow.com/questions/3754786/calling-non-static-method-with – depz123 Mar 11 '14 at 10:18

1 Answers1

1

Resulting in output xy without generating any errors or warnings.

No way. The error reporting must have been turned off on that environment. That would have definitely produced a Strict Standards warning notice.

Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126
  • So it does. I learnt something new, but not what I initially thought - `E_ALL` does not include `E_STRICT` before 5.4. I'll accept this as the answer when the time limit is reached. – Mitch Satchwell Mar 11 '14 at 10:20
  • That is correct. FYI the [**changelog**](http://in1.php.net/manual/en/function.error-reporting.php#refsect1-function.error-reporting-changelog) – Shankar Narayana Damodaran Mar 11 '14 at 10:21