Search code examples
phpclassmethodsmodelradix

Referencing a model from a string


How can I call the model from a string?

$model = 'User';

I tried the following:

\App\.$model::get();
\App\{$model}::get();
\App\.{$model}::get();
\App\${$model}::get();
\App\.${$model}::get();

I feel like I'm missing something although a workaround it would be:

$model = 'App\User';
$model::get();

But for learning purposes im trying to see how i can mix it up like above.


Solution

  • Make a string out of the whole thing:

    namespace App;
    
    class Model {
        public static function go() {
            echo 'yay!';
        }
    }
    
    $someString = 'Model';
    $className = 'App\\' . $someString;
    var_dump(new $className());
    $className::go();
    

    Working example.