0

Hello. I am curious if it is possible to create functions dynamically in such a way, that (1) the names of the functions to be retrieved from an array and (2) these names could be used also inside the functions. I have a code that is solving the first problem, any ideas how to solve problem 2? Thanks.

<?php

$myarray = ['myvalueone','myvaluetwo','myvaluethree','myvaluefour','myvaluefive'];

for($i=0, $n=count($myarray); $i<$n; $i++)
{
    $functionname = $myarray[$i];
    $$functionname = function(){
        echo 'The name of the function is ... .';
    };
}

$myvaluetwo(); // The result need to be: The name of the function is myvaluetwo.

?>
4
Contributors
11
Replies
63
Views
4 Years
Discussion Span
Last Post by eburlea
Featured Replies
  • Have you checked out the create_function() function? See here: http://php.net/manual/en/function.create-function.php Read More

  • <?php $function_names = ['myvalueone','myvaluetwo','myvaluethree','myvaluefour','myvaluefive']; $functions = array(); foreach($function_names as $function_name){ // You need to use (the variable) to import it in the function $functions[$function_name] = function() use ($function_name){ // <-- USE echo 'The name of the function is ', $function_name, PHP_EOL; }; // Store nicely in array call_user_func($functions[$function_name]); // I … Read More

0

I could get the result with create_function() in this way:

$myarray = ['myvalueone','myvaluetwo','myvaluethree','myvaluefour','myvaluefive'];

$func = create_function('$functionname', 'echo "The name of the function is $functionname.";');

for($i=0, $n=count($myarray); $i<$n; $i++)
{
    $func($myarray[$i]);
    echo '<br />';
}

Actually I need to use these dynamically created functions in a multithreading script which extracts from the database a certain number of categories that need to correspond to the name of a function. I know how to run all functions simultaneously, but I do not know how to get the category name as name of the function and as parameter in the same time. And I am not sure if I can use here '$func($myarray[$i])' as parameter to an object instead of a simple function name as below:

function first ()
{
    for($i=1; $i<=10; $i++)
    {
        mkdir('first ' . $i);
        sleep(5);
    }
}

function second()
{
    for($i=1; $i<=10; $i++)
    {
        mkdir('second ' . $i);
        sleep(5);
    }
}

function third()
{
    for($i=1; $i<=10; $i++)
    {
        mkdir('third ' . $i);
        sleep(5);
    }
}

// create 3 thread objects
$t1 = new Application_Plugin_Thread( 'first' );
$t2 = new Application_Plugin_Thread( 'second' );
$t3 = new Application_Plugin_Thread( 'third' );

// start them simultaneously
$t1->start( 1, 't1' );
$t2->start( 1, 't2' );
$t3->start( 1, 't3' );

// keep the program running until the threads finish
while( $t1->isAlive() && $t2->isAlive()  && $t3->isAlive() ) {

}
0

I did the following, and that worked. Is that any help or am I still not understanding your problem correctly?

<?php
$function_content = '
    if($arg1 == \'test\')
    {
        echo \'Yes\';
    }
    else
    {
        echo \'No\';
    }
    ';

$function = create_function('$arg1', $function_content);

$function('test'); // Returned "Yes".
$function('testt'); // Returned "No".
0

No, this is not what I am looking for.

Let me explain in other words...

I have a database with 20 categories. I need to be created 20 functions which names should coincide with the category names. Also I need to use each function name inside the corresponding function as parameter. This code need to be written one time and when I add a new category into the database, I will have now 21 functions, without changing the code.

0

Hmmm well I have no better idea then than to write all your functions to an external file each time the list of categories gets changed, and then including that file in each file that you need to use those functions in.

You can write to a file using file_put_contents(), for example. What I'm saying is: generate those functios as you would write them in a new PHP file, and then actually write them to a new (or existing) PHP file.

If anyone has any better ideas, I'd love to hear them. If noone is taking the trouble to read such a long post and my answer is not what you are looking for, I would suggest starting a new topic with the same question :). Hope I could be of help anyway!

0

@minitauros

Thank you for your answers anyway, even if they cannot be implemented in this particular situation, I will keep them in mind and use when the case will come.

I am still googling the web for the answer, have tried many codes, but no luck.

Edited by eburlea: spelling

0

The problem is that the loop goes to overwrite the function value and even the name. But this seems to work fine for me:

<?php
$myarray = array('myvalueone','myvaluetwo','myvaluethree','myvaluefour','myvaluefive');
$n=count($myarray);
for($i=0; $i < $n; $i++)
{
    define('FUNCTIONNAME'.$i,$myarray[$i]); # define the value
    ${$myarray[$i]} = create_function('$name = FUNCTIONNAME'.$i, 'return "The name of the function is ". $name;');
}
echo $myvaluefive();
echo "\n";
echo $myvalueone();
?>

Output:

The name of the function is myvaluefive

The name of the function is myvalueone

I tried also __FUNCTION__ instead of $name but it outputs __lambad_func or closure depending on the methods: create_function or anonymous functions. Hope it helps.

Edited by cereal

1
<?php
$function_names = ['myvalueone','myvaluetwo','myvaluethree','myvaluefour','myvaluefive'];
$functions = array();
foreach($function_names as $function_name){
    // You need to use (the variable) to import it in the function
    $functions[$function_name] = function() use ($function_name){ // <-- USE
        echo 'The name of the function is ', $function_name, PHP_EOL;
    }; // Store nicely in array
    call_user_func($functions[$function_name]); // I like to be explicit
}
?>
Votes + Comments
nice solution!
0

@CodeAngry
I tried to adapt my code to yours, now it's much better:

<?php
$function_names = array('myvalueone','myvaluetwo','myvaluethree','myvaluefour','myvaluefive');
$functions = array();
foreach($function_names as $function_name){

    ${$function_name} = function($name = false) use ($function_name){ // <-- USE
        return 'The name of the function is ', ($name === false ? $function_name:$name), PHP_EOL;
    };
}

echo $myvalueone();
echo $myvaluetwo('hello');
?>
0

Thank you so much all for helping me and providing many variants. The last example is exactly what I am looking for.

1

I have found another solution using a class.

class CreateFunction
{
    function __construct()
    {
        $function_name = ['myvalueone','myvaluetwo','myvaluethree','myvaluefour','myvaluefive'];

        for($i=0,$n=count($function_name); $i<$n; $i++)
        {
            $this->$function_name[$i] = create_function('', 'echo "The name of the function is ' . $function_name[$i] . '.<br />";');
        }
    }

    public function __call($method, $args)
    {
        if(property_exists($this, $method)) {
            if(is_callable($this->$method)) {
                return call_user_func_array($this->$method, $args);
            }
        }
    }
}

$object = new CreateFunction();
$function_names = ['myvalueone','myvaluetwo','myvaluethree','myvaluefour','myvaluefive'];

for($i=0,$n=count($function_names); $i<$n; $i++)
{
    $object->$function_names[$i]();
}
Votes + Comments
thanks for sharing!
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.