Search code examples
phpfilereturnargumentsanonymous-function

PHP return data from anonymous in file


I have seen a file that looks kind of like this:

my-file.php

<?php
return function($some, $args) {
  return array(
    'foo' => 'my first template variable',
    'bar' => 'my second template variable'
  );
};

It's an anonymous function that return data and it is somehow fetched and used somewhere else.

How can I fetch data from a file that looks like this?

I've been searching and looked into other questions but I did not find anything like it.


Solution

  • So the relevant documentation can be found on the include document and the anonymous function document.

    To summarise, included / required files can return values. These can then be assigned to variables.

    In this case you could do the following:

    $callable = require 'my-file.php';
    

    This would assign the anonymous function to $callable at which point you can treat it as a standard closure (because that's what it is) and call it as you would a function:

    $callable($anyargs, $needed);
    

    Which in this case would return the data in the array.