Yohan Leafheart Yohan Leafheart - 1 year ago 71
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 Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download