Export functions in PHP à la Javascript
Warning: This post is totally useless. It is the result of a fun private company thread.
Export functions in Javascript
In Javascript, a file can export functions like this:
And then we can import this function in another file like this:
;
21; // 42
Is it possible with PHP?
Export functions in PHP
Every entity is public in PHP: Constant, function, class, interface, or trait. They can live in a namespace. So exporting functions in PHP is absolutely useless, but just for the fun, let's keep going.
A PHP file can return an integer, a real, an array, an anonymous function, anything. Let's try this:
And then in another file:
Great, it works.
What if our file returns more than one function? Let's use an array (which has most hashmap properties):
To choose what to import, let's use the list
intrinsic.
It has several forms: With or without key matching, long (list(…)
) and
short syntax ([…]
). Because we are modern, we will use the short
syntax with key matching to selectively import functions:
Notice that times2
has been aliased to $mul
. What a feature!
Is it useful? Absolutely not. Is it fun? For me it is.