-1

While I understand that static methods can be invoked through a variety of approaches, such as:

A::staticFunction();

OR

$class = 'A';
$class::staticFunction();

OR

$a = new A(); // Assume class has been defined elsewhere
$a->staticFunction();

However, could someone please explain why the following won't work, and if possible, how to make this work (without resorting to the solution provided):

// Assume object $b has been defined & instantiated elsewhere
$b->funcName::staticFunction(); // Where funcName contains the string 'A'

This produces the following PHP parse error:

Parse error: syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM)

Typical working solution (follows second approach) (preferably avoid if possible):

// Assume object $b has been defined & instantiated elsewhere
$funcName = $b->funcName; // Where funcName contains the string 'A'
$funcName::staticFunction();
robnov
  • 1

1 Answers1

0

The :: operator is used to refer to a non-instanced class. That means you're referencing either static methods or variables, or const. The hallmark of static methods is that they cannot work with your instance. They are, essentially, stand-alone functions and cannot use $this to refer back to the instance of your class.

As such, you cannot refer to a static method by referencing the instance. You need to use

self::function();

or

$this->function();

While the latter makes it look like it might be part of the instance, it's included for completeness only.

Machavity
  • 30,841
  • 27
  • 92
  • 100
  • Thanks for responding so quickly, but it's not referring to a static method by referencing the instance. It's referencing a property of an instance, which is a string, not an object. – robnov May 26 '14 at 14:26
  • You can't reference `static` properties by referring to an instance, though. `$b` is an instance (as denoted by `->`). – Machavity May 26 '14 at 14:28
  • I get what you're saying, but technically, as I said, while an instance is included in the statement, it's referencing the property of an instance, which is not using the instance itself to call the static method, but the result of the instance's property, which is a string. So, effectively, it should behave in the same way as the second example ($class::staticFunction()). Do you know how to replicate this behaviour, in the way I originally described? – robnov May 26 '14 at 14:35