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
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");