Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling static method with static class variable as class name in php

I know you can call static methods using variable as class name like so:

$className = "Foo";  
$className::Bar(); //works  

But when i'm trying to use static property as variable like this:

self::$className = "Foo";
self::$className::Bar();  //doesn't

it gives me the following parse error on line where i'm trying to call the method:

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

So how can i call that method using static property and is that even possible with syntax somewhat similar to what i described(w/o call_user_func and creating local variable that stores self::$className)?

like image 649
Danil Solodunov Avatar asked Oct 16 '25 18:10

Danil Solodunov


1 Answers

You could do that:

$tmp = self::$className;
$tmp::Bar();

Edit

Based on your comments it seems your problem is more about OOP design than it is about syntax. Furthermore, you keep adding new restrictions every time a solution is given, which makes it difficult to provide a relevant answer.

Anyway, I'll try to summarize your options. The syntax you want does not exist (at the moment, anyway), so you have to work around it one way or another. Yes, this is annoying, and yes this means that you will have to make concessions. But that's how it is.

Here are your options so far:

  • Use call_user_func or forward_static_call or similar.
  • Use a temporary local variable. Possibly wrap that into a method if it's really bothering you (e.g. static function call($method) { $tmp = self::$classname; return $tmp::$method(); } and then use self::call('bar');)
  • Refactor your object design using instances instead of static methods so that you don't need to do that anymore.
  • Use some other terribly ugly and dangerous hack (e.g. eval(self::$classname.'::bar();'); and hope it won't come bite you in the butt.
like image 95
rlanvin Avatar answered Oct 19 '25 08:10

rlanvin