Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

naykel's avatar

Defining dynamic models for traits

I am learning about traits and need some help to understand defining models for re-usability.

Both of the following examples to define the model seem to work but I don't really understand the differences. Is there any reason why I should use one methods to over the other?

// define the model and namespace
private $modelA = '\App\Models\Category';

public function getItemsA()  {
    return $modelA::all();
}


// define the model class
private static $modelB = Category::class;

public function getItemsB() {
    return self::$modelB::all();
}
0 likes
2 replies
Sinnbeck's avatar

A few differences. First example uses a dynamic property while the second uses a static. Static properties are bound to the class and not the specific model. So if we change the static one at runtime, it gets changed for all instances of the class.

And secondly the first uses a cardcoded string for the class path. The second uses code to let php find the path.

echo Category::class; // shows \App\Models\Category 

Please or to participate in this conversation.