0

According to https://www.tutorialspoint.com/php/php_constants.htm a normal costant is define by using define() function plus a value:

define('TEST', 123);

I think it would be interesting and useful if there were a way to define a constant with a function inside:

define ('ME', function($test){
   if($test == true){
       return "Whats up";
   }else{
       return "whats down";
   }
}); 

Then perhaps I could do something like this?

 if($I_Said === ME($val)){
     do something;
 }

Is there a such a way to do this?

LukeDS
  • 141
  • 8
  • 1
    and the question is? – Lelio Faieta Sep 21 '18 at 10:51
  • 1
    Sorry, if there is a way to do this – LukeDS Sep 21 '18 at 10:51
  • 2
    No, it's [not possible](http://php.net/manual/en/function.define.php). It's would be an awful way of defining global functions anyway. – Mike Doe Sep 21 '18 at 10:52
  • 1
    Possible duplicate of [How to define global functions in PHP](https://stackoverflow.com/questions/4458837/how-to-define-global-functions-in-php) – Philipp Maurer Sep 21 '18 at 10:53
  • 1
    Why would you want to do it this way? – ka_lin Sep 21 '18 at 10:54
  • 1
    @ka_lin just for curiosity mate, learning only. – LukeDS Sep 21 '18 at 10:56
  • 1
    @LukeDS ahh ... gotcha – ka_lin Sep 21 '18 at 10:56
  • 1
    If this was possible, a big downside would be that functions and constants would now have an overlapping namespace. If I say `define ('echo', function() { ... })` then PHP wouldn't know if I wanted to run the native `echo` or my new defined function. It would be a breaking-change to any code that defined a constant with the same name as an internal function. – iainn Sep 21 '18 at 11:00
  • 1
    Different lookup tables. Once the interpreter encounters `FOO()` it will only search the function declaration list. It won't even consider `define("FOO", "BAR");` for overrides. – mario Sep 21 '18 at 11:04

1 Answers1

3

There's no syntactical or other important difference on the caller side to:

function ME() {}

if ($I_Said === ME($val))

So, just do that.

deceze
  • 510,633
  • 85
  • 743
  • 889
  • 1
    Yeah i know this is possible. I was just wondering if my question was possible – LukeDS Sep 21 '18 at 10:55
  • 1
    What would be the advantage if it was? – deceze Sep 21 '18 at 10:55
  • 1
    dont know, perhaps none. But would be nice to learn if there was one. Just to understand what PHP is capable of doing really. – LukeDS Sep 21 '18 at 10:58
  • 1
    And no, there are technical reasons against it. The interpreter needs to know whether `ME()` refers to a function or a constant which should be executed as a function, which is quite a big deal, and the current solution is that it simply can never refer to a constant. – deceze Sep 21 '18 at 10:59