Home > Software design >  Convert a string of items into comma seperated variable names and inject into function
Convert a string of items into comma seperated variable names and inject into function

Time:01-26

I am trying to convert my string on id's into variable names and inject them into my function.

I have a json object with the following information in it:

Object
(
    [files]         =>    file1.php,fie2.php
    [dependencies]  =>    db,templates
    [classname]     =>    SomeClass
)

I am able to loop through everything and get it to work with a single variable name, but when there is more than one dependency, I need to loop through them, make them variables, and then pass to a function depending on how many are needed dynamically from this object above.

// First I make sure the dependency object exists, this one has 'db,templates' in it
if (!empty($json_data->dependencies)) {

    // I explode them into an array, to see if there is more than one
    $dependence_string = explode(",", $json_data->dependencies);

    if (is_array($dependence_string)) {
        // I make a dummy variable
        $dependencies = NULL;
        foreach ($dependence_string as $dependency) {
            $dependencies[] = '$' . $dependency; 
        }

        // Now i have an array with two values "$db", "$templates"
        // This gets inserted as new SomeClass(Array()); but I need to
        // somehow be able to convert it to new SomeClass($db, $templates);
        $some_value = new $json_data->classname($dependencies);

    } else {
        // This is easy to handle and is done already
    }

Now i have an array with two values "$db", "$templates" and this gets inserted as new SomeClass(Array()); but I need to somehow be able to convert it to new SomeClass($db, $templates); and keep them comma separated as variables from their string names.

What method would I use for this? I tried implode but it still sends as a string and I need to convert it to individual items and send however many the current script needs to run.

CodePudding user response:

Got it to work with the following code:

foreach ($dependence_string as $dependency) {
    $dependencies[] = '$' . $dependency; 
}
$some_value = (new ReflectionClass($json_data->classname))->newInstanceArgs($dependencies);

CodePudding user response:

The splat operator could be the solution to your issue.

<?php
declare(strict_types=1);
namespace Marcel;

class SomeClass
{
    protected string $db;

    protected string $templates;

    public function __construct(string $db, string $templates)
    {
        $this->db = $db;
        $this->templates = $templates;
    }
}

foreach ($dependence_string as $dependency) {
    $dependencies[] = '$' . $dependency; 
}

$class = new SomeClass(...$dependencies);

Type hinting is not required but would be nice. To keep the example simple, strings are used here.

  •  Tags:  
  • Related