N
N
nepster-web2014-07-16 21:33:21
PHP
nepster-web, 2014-07-16 21:33:21

How to organize an instance of a class called through call_user_func ?

There was such a question.
I am writing a ranking system for the user, the description of each rank will be in a separate class.
$rangs - an array of all ranks

foreach($rangs as $rang) {
            
            $alias = ucwords($rang['alias']);
        
            // проверяем наличие класса для определения ранга 
            if(!class_exists($pathToRangsClass.$alias)) {
                throw new \Exception('Не найден класс '.$pathToRangsClass.$alias);
            }
            
            $verify = call_user_func("\\modules\\rangs\\libraries\\{$alias}::verify", $userId);
            
       }

The class method is called, everything is fine. Now in the class itself I need to organize something like:
public static function getInstance($className=__CLASS__)
    {
        return new $className;
    }

to have access to $this. But there is no way to organize it.
These are the jokes that don't work:
$verify = call_user_func("\\modules\\rangs\\libraries\\{$alias}::getInstance", $userId);
$verify = call_user_func("\\modules\\rangs\\libraries\\{$alias}::getInstance()->verify", $userId);

Answer the question

In order to leave comments, you need to log in

4 answer(s)
D
Dmitry Entelis, 2014-07-16
@DmitriyEntelis

Never use call_user_func. It works very slowly.

S
Sergey, 2014-07-16
Protko @Fesor

Why do you like static methods so much? Why do you need classes then? Why not just spread the functions by namespace?

N
Nazar Mokrinsky, 2014-07-17
@nazarpc

Try like this:

$verify = call_user_func(
    [
        "\\modules\\rangs\\libraries\\{$alias}",
        "getInstance"
    ],
    $userId
);

In the array, the first element is the name of the class or object instance, the second - the name of the method.
Read more in the official source: php.net/manual/en/language.types.callable.php
But based on what I understood from your wording, you need something like:
$verify = call_user_func([
    "\\modules\\rangs\\libraries\\{$alias}",
    "getInstance"
])->verify($userId);

A
AxisPod, 2014-07-17
@AxisPod

OOP is not your way?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question