Although about half the content covered here has been theory, the other half has been some pretty tricky PHP code to do things that most people wouldn't dream of. Yes, PHP is a scripting language, and yes it is nothing like as fast as C or Java, but that doesn't mean you cannot use it in weird and wonderful ways.
Writing your own sub-language in PHP is probably the most challenging thing you can do in the language, so you should pat yourself on the back for making it this far. However, like any addiction, you are probably already trying to think up new ways to do more programming on your new creation, and I am happy to oblige:
Add more operators. / and - spring to mind, but also . for concatenation.
Let variables include numbers, such as myvar2
Have their compiler track line numbers, then have it print out meaningful error messages
Add loops (difficult to do unless you fully grasp the stack concept)
Add basic function calls. That is, let people call the PHP functions but not define their own. If you really want a challenge, let them define their own function calls also. I wouldn't attempt the extra challenge unless you have already successfully implemented loops.
There is just one last thing I want to mention before I leave you to your own devices, and that is that you should really be using a PHP IDE when you work on your compiler. When writing the code for this chapter I used Zend Studio entirely, simply because I relied very heavily on its debugger to step through my code and figure out where things were going wrong (yes, I put bugs in code too!) If you are serious about writing a mini-language for PHP, get an IDE that comes with a debugger or you will likely pay for it in sleepless nights hacking away at your code.
Want to learn PHP 7?
Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!
If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!
Next chapter: Summary >>
Previous chapter: The script in (almost) full
Home: Table of Contents
Copyright ©2015 Paul Hudson. Follow me: @twostraws.