Edit report at https://bugs.php.net/bug.php?id=66368&edit=1
ID: 66368
Comment by: chriswarbo at gmail dot com
Reported by: chriswarbo at gmail dot com
Summary: Operators should also be functions
Status: Open
Type: Feature/Change Request
Package: *General Issues
Operating System: Irrelevant
PHP Version: Irrelevant
Block user comment: N
Private report: N
New Comment:
Oops, $example_1 should use $f not $g.
Previous Comments:
------------------------------------------------------------------------
[2013-12-30 08:30:35] chriswarbo at gmail dot com
Description:
------------
PHP's operators (+, -, *, /, ||, &&, etc.) can be tedious to use, since they are
second-class citizens compared to functions. They can't be abstracted (example 1), can't
be used as callbacks (example 2) and must be hard-coded (example 3).
Operators with non-symbolic names, eg. "or", "and", "xor", etc. can be
defined as functions right now without breaking existing code, since their names look like valid
functions and are guaranteed to be available (example 4). For consistency, it may be desirable to
create synonyms for operators with symbolic names, eg. "+", "-", "*",
etc. (example 5). Ambiguities can be handled trivially (example 6). Alternatively, the symbolic
names could be used directly (example 7).
In every project I work on, I inevitably end up writing these as in-line lambdas, then eventually
refactor them out into a library. I'm sure I'm not alone. If PHP stopped treating
operators differently from functions, large amounts of boilerplate code could be scrapped and the
redundant effort of wrapping these in lambdas over and over again could be spared.
Test script:
---------------
$f = 'or';
$example_1 = $g($g(TRUE,
$g(FALSE, TRUE)),
FALSE);
$example_2 = array_reduce(array(TRUE, FALSE), $f, FALSE);
$example_3 = call_user_func(
function($op) {
return $op(TRUE, FALSE)
},
$f);
// Example 4
function or($x, $y) { return $x or $y; }
// Example 5
function mult($x, $y) { return $x * $y; }
// Example 6
function plus($x, $y = NULL) { return is_null($y)? +$x : $x + $y; }
function minus($x, $y = NULL) { return is_null($y)? -$x : $x - $y; }
$example_7 = call_user_func('+', 10, 5);
Expected result:
----------------
$example_1 == TRUE;
$example_2 == TRUE;
$example_3 == TRUE;
or(TRUE, FALSE) == TRUE;
mult(5, 3) == 15;
plus(10) == 10;
plus(4, 3) == 7;
minus(5) == -5;
minus(8, 7) == 1;
$example_7 == 15;
Actual result:
--------------
$example_1 -> Undefined function 'or'
$example_2 -> Undefined function 'or'
$example_3 -> Undefined function 'or'
$example_4 -> Unexpected T_LOGICAL_OR
$example_7 -> Warning: First argument is expected to be a valid callback
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=66368&edit=1