1

Let's assume, we have an array with anonymous functions as values. It has following contents:

  $fpool = [
    'f1' => function($a){
        if($a > 0){
          return [$a*$a, $a+$a];
        }
        return 0;
     },

    'f2' => function($a){
       if($a > 0){
         return [$a*3, $a+2];
       }
       return 1;
    }
];

I want to take some values and save them to separate file without copy/paste.

Is it possible for example to save $fpool['f2'] to separate file for later include?

The file to include must have followng content:

   <?php
       return ['f2' => function($a){....}]

Because its a closure I can't serialize() or do var_export()

5
  • If your include file absolutely has to have that particular format, you will need to merge the array you are getting returned, with your existing $fpool yourself then. Commented Aug 8, 2023 at 13:48
  • Does this answer your question? Enabling preg_replace_callback() replacement function if it's loaded from string Commented Aug 8, 2023 at 13:51
  • I don't think you have access to the source code of the function behind $fpool['f2'], unless you parse the original PHP script in which the code exists. See for instance the answer to this question. Commented Aug 8, 2023 at 13:55
  • 1
    You could utilise a package like opis/closure. Since the concept is to utilise a wrapper object, this would require the package being required prior to unserializing them in your seperate file. Commented Aug 8, 2023 at 19:52
  • Slightly off-topic: Do you use namespaces and classes in this project? That would help to maintain the project over time. Storing anonymous functions in files then including them is very error-prone IMHO. Commented Aug 8, 2023 at 23:57

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.