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()

user2624744
  • 693
  • 8
  • 23
  • 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. – CBroe Aug 08 '23 at 13:48
  • Does this answer your question? [Enabling preg\_replace\_callback() replacement function if it's loaded from string](https://stackoverflow.com/questions/76172829/enabling-preg-replace-callback-replacement-function-if-its-loaded-from-string) – shingo Aug 08 '23 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](https://stackoverflow.com/questions/7026690/reconstruct-get-source-code-of-a-php-function). – KIKO Software Aug 08 '23 at 13:55
  • 1
    You could utilise a package like [opis/closure](https://github.com/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. – Jaquarh Aug 08 '23 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. – A.L Aug 08 '23 at 23:57

0 Answers0