Mark
Mark

Reputation: 18184

What is the correct way to call a static method in PHP?

When I call my static method by static::some_method(); it gives me the following error:

Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM, expecting T_VARIABLE in /some/path/SomeClass.class.php on line 15

If I replace static with the class name it works of course, but what is the correct way to call a static method without using the classname?

Upvotes: 1

Views: 220

Answers (2)

Umbrella
Umbrella

Reputation: 4788

If you are within the context of the class then

self::method();
static::method();

...will both work, with different behaviors related to late static binding.

If you are not in the context of a class, then you need to use the classname the method belongs to:

SomeClass::method();

Otherwise you'll get that goofy hebrew error, T_PAAMAYIM_NEKUDOTAYIM, which means "double colon" in English.

Upvotes: 8

Grzegorz Rożniecki
Grzegorz Rożniecki

Reputation: 27995

Use

ClassName::some_method()

to invoke static method (not using static keyword) or, if you are inside one that class, use

self::some_method()

where self is a keyword (i.e. inside another method).

Upvotes: 2

Related Questions