Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing static methods as arguments in PHP

Tags:

php

class

static

In PHP is it possible to do something like this:

myFunction( MyClass::staticMethod ); 

so that 'myFunction' will have a reference to the static method and be able to call it. When I try it, I get an error of "Undefined class constant" (PHP 5.3) so I guess it isn't directly possible, but is there a way to do something similar? The closest I've managed so far is pass the "function" as a string and use call_user_func().

like image 527
Allan Jardine Avatar asked Jul 25 '12 17:07

Allan Jardine


People also ask

Can we pass arguments in static method?

Voting is disabled while the site is in read-only mode.

Why not use static methods PHP?

It's generally a bad idea to depend on static methods because they make substitution (and therefore specialising or testing) difficult. It looks like what you have is 10 independent classes that all inherit from the same interface. But without explaining what those functions do, its impossible to say how to improve.

Can we inherit static method in PHP?

The static variable is used in the A and B classes, yet the method is inherited so it is actually the same code which is called. Until PHP 8.0, there would be a distinct static variable depending on which class is called.

What is static method in PHP give an example?

To add a static method to the class, static keyword is used. They can be invoked directly outside the class by using scope resolution operator (::) as follows: MyClass::test(); Example: This example illustrates static function as counter.


1 Answers

The 'php way' to do this, is to use the exact same syntax used by is_callable and call_user_func.

This means that your method is 'neutral' to being

  • A standard function name
  • A static class method
  • An instance method
  • A closure

In the case of static methods, this means you should pass it as:

myFunction( [ 'MyClass', 'staticMethod'] ); 

or if you are not running PHP 5.4 yet:

myFunction( array( 'MyClass', 'staticMethod') ); 
like image 53
Evert Avatar answered Sep 25 '22 07:09

Evert