Yohan Leafheart Yohan Leafheart - 23 days ago 10
PHP Question

How can I create a new operator in PHP?

I see myself doing the following code for default assigment all the type on PHP

$variable = $variable ? $variable : 'default value';


I know that with 5.3 I can do

$variable = $variable ?: 'default value';


I would like to further simplify it by being able to just do

$variable ?= 'default value';


and have the variable reassigned in case it evaluates to false. Is it possible to create that assignment? Do I have to compile my own version of php to do that?

Answer

You cannot create new operators in PHP without changing the PHP source.

And you don't want to change it, trust me. Sure, it'd be easy enough - PHP is open source and uses a straightforward LALR(1) parser which you could easily modify - but that would make your code incompatible with the standard PHP implementation. You would thus very much restrict who can run the code - which will probably be nobody apart from you, as nobody else will care to modify their PHP engine just to run your code.

Update: I wrote a small tutorial on how to add new syntax (like operators) to PHP: http://nikic.github.com/2012/07/27/How-to-add-new-syntactic-features-to-PHP.html