0

I'm trying to introduce few things that I've learned in languages like Scala and Haskell to PHP and experiment with it. To give a concrete example, I would like to extend the PHP syntax to be able to do something like the following:

array_map( _ + 1, [1,2,3]) // returns [2,3,4]

As I understand it "extending the PHP language" means two things:

  • writing an extension in C and putting it as a php.ini extension stanza
  • extending the language (parser) itself (Zend Engine?) which is written in C

I think I want the second item but I see things like xdebug that (to me) pretty much delve deep into PHP internals. I was kinda hoping that perhaps I can extend PHP syntax without the need to wrestle with its parser?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Ashkan Kh. Nazary
  • 21,844
  • 13
  • 44
  • 68
  • 1
    Just curious. What is `array_map( _ + 1, [1,2,3])` supposed to do? – Amal Murali Dec 28 '13 at 10:01
  • Map function like `function($x){return $x+1;}` on the array @AmalMurali – Cthulhu Dec 28 '13 at 10:02
  • 1
    @Cthulhu: I see. What does `_` mean? Each array element? – Amal Murali Dec 28 '13 at 10:04
  • Not exacly - just missing value. So it kind of turns into function taking a value and returning result for it @AmalMurali – Cthulhu Dec 28 '13 at 10:06
  • @AmalMurali it means the argument to the anonymous function that is written as `_ + 1`. You can read it as : `f(_) = _ + 1` – Ashkan Kh. Nazary Dec 28 '13 at 10:17
  • 1
    No, this is not possible. You can't do syntax changes from an extension. – NikiC Dec 30 '13 at 23:41
  • @NikiC Would you please kindly point me to the right direction ? – Ashkan Kh. Nazary Dec 31 '13 at 16:20
  • @ashy_32bit I have a blog post on the topic: http://nikic.github.io/2012/07/27/How-to-add-new-syntactic-features-to-PHP.html What you want in particular will not be easily to implement though, not with that syntax at least. You should try a shortened lambda syntax first. – NikiC Dec 31 '13 at 16:57
  • Thinking a bit further, what you *can* do from an ext is make `_` an object (you can't use a `_` const though, will have to be a variable `$_` or a function call or something) and then overload all supported operands for it, so that `_ + 1` returns an object that has an `__invoke` method doing the +1 operation. But that seems like a rather ugly, slow and incomplete approach. – NikiC Dec 31 '13 at 17:01
  • Just an FYI: [`_`](http://php.net/_) already exists in PHP. It's an alias for the `gettext()` function. So, using `_` in this kind of syntax might be a little hard. – gen_Eric Jan 06 '14 at 16:30

1 Answers1

4

To modify PHP's syntax you need to modify its parser. This is not something you can do with an extension. Xdebug might delve deep into the engine, but it only reads information.

Derick
  • 35,169
  • 5
  • 76
  • 99