4

I am having a situation where, I have to use static method but here my class name is stored in some variable.

As per this link: http://php.net/manual/en/keyword.paamayim-nekudotayim.php#50310 I can not use variable with ::.

for reference my code looks like below and I am using Yii2 for this stuff:

$modelName = "User";

$query = $modelName::find();

Obviously it is giving me error, Link I have given is 10 years old from now so Just wanted to check if is there any alternative to this situation.

Update:

$query = AdminUser::find(); // Works Fine

$name = 'AdminUser';
$query = call_user_func("$name::find");
// Giving Below Error
call_user_func() expects parameter 1 to be a valid callback, class 'AdminUser' not found
Avinash
  • 6,064
  • 15
  • 62
  • 95
  • According to this [link](http://php.net/manual/en/language.oop5.static.php), as of php 5.3 you can store the classname in a variable. what is the error you are getting? Is the function you are calling defined as static? – bryant Aug 18 '15 at 05:31
  • @bryant yes I am calling the static method. – Avinash Aug 18 '15 at 05:35
  • You couldn't in 2005, when the comment was written. What's your PHP version? – Álvaro González Aug 18 '15 at 06:03
  • @ÁlvaroG.Vicario I am using 5.5.12 – Avinash Aug 18 '15 at 06:04
  • Then [it should work](http://3v4l.org/OsSMK). Can you please edit the question and paste the error message? Please use the clipboard to copy the actual error message, don't just describe it with your own words. – Álvaro González Aug 18 '15 at 06:09

1 Answers1

2

You need to specify class name including namespace. See php docs about it. So your call should look like this:

$name = __NAMESPACE__ . '\AdminUser';
$query = call_user_func("$name::find");

Note that __NAMESPACE__ constant returns current namespace. So if your AdminUser class belongs different namespace you need to specify it. E.g.:

//your current namespace:
namespace app\controllers;
//and somewhere in your method:
$name = 'common\models\AdminUser';
$query = call_user_func("$name::find");
Tony
  • 5,797
  • 3
  • 26
  • 22