btwael / mammouth

Unfancy PHP
http://mammouth.boutglay.com
MIT License
214 stars 22 forks source link

Inner functions #5

Closed philip-peterson closed 11 years ago

philip-peterson commented 11 years ago

I can see a number of functions issues coming up. The first, which I think is an excellent thing that a language compiling to PHP could implement, is useful inner functions.

In PHP you can do this:

<?php
function hello() {
   echo "Hello";
   function there() {
      echo " there";
   }
   there();
}

If you then call hello(), it will work, printing "Hello there". If you call hello() a second time, however, you'll get:

Hello
Fatal error: Cannot redeclare there() (previously declared in -:5) in - on line 4

Because as much as it looks like one, there is not actually an inner function; it's a globally scoped one. It's just not defined until a call to hello() is made, and after that, it persists, which is what causes the "redeclare" error when it tries to run the code again. The result is that PHP doesn't really have inner functions, which defeats the whole point of having syntax for them.

Now, if Mammouth is a smart language with a smart compiler, it can do something /useful/ with inner functions for PHP. Something, perhaps, like this:

<?php
$hello = function () {
   echo "Hello";
   $there = function() {
      echo " there";
   }
   $there();
}

This would make for enormously nicer code bases. There may be the occasional use case where you need to export a function so normal PHP code can read it without being super weird, but there could be a special syntax for that.

btwael commented 11 years ago

Hi @philip-peterson , Now you can declare Inner functions

hello = ->
   echo("Hello")
   there = ->
      echo(" there")
   $there()
$hello()

Compiled to

$hello = function() {   
    echo('Hello');
    $there = function() {   
        echo(' there');
    };
    $there();
};
$hello();

To see example: http://btwael.github.io/mammouth/#try:{{%0Ahello%20%3D%20-%3E%0A%20%20%20echo%28%22Hello%22%29%0A%20%20%20there%20%3D%20-%3E%0A%20%20%20%20%20%20echo%28%22%20there%22%29%0A%20%20%20%24there%28%29%0A%24hello%28%29%0A}}