Im wondering if its possible to init a class from a ‘mapping’ in a PHP model.
For instance, in a model, if I map strings to class names in an array, can i then pass a string to map to a specific class and then initialise it, if that makes sense.
In my model if I have an array;
public const $mappingArray = [
'first-string-name-here' => 'FirstClassName',
'second-string-name-here' => 'SecondClassName',
];
Would it be possible to pass the string in a controller method and receive a class;
2
Answers
Yes, it’s possible to create a mapping of strings to class names in PHP and then dynamically instantiate a class based on a string in a controller method. You can use PHP’s built-in
class_exists()
andnew
operators to achieve this.Here’s an example of how you can do it:
In your model:
In your controller method:
You can call the
createInstanceFromClassString
method in your controller, passing the string you want to map to a class:This way, you can dynamically create instances of classes based on the strings you provide, as long as they are mapped in your model’s mapping array.
You can map strings to class names and then instantiate those classes dynamically in PHP. Here’s how you can achieve this:
Define Your Classes:
Model with Mapping Array:
Controller Method to Instantiate Class:
Usage:
This way, you can map strings to class names in your model and then use those mappings to dynamically instantiate classes in your controller.