I have a function that is effectively a replacement for print, and I want to call it without parentheses, just like calling print.
# Replace print $foo, $bar, "\n"; # with myprint $foo, $bar, "\n";
In Perl, you can create subroutines with parameter templates and it allows exactly this behavior if you define a subroutine as
sub myprint(@) { ... }
Anything similar in PHP?
When we call a function with parentheses, the function gets execute and returns the result to the callable. In another case, when we call a function without parentheses, a function reference is sent to the callable rather than executing the function itself.
Attributes (e.g. imag) are like variables inside the object so you don't use parentheses to access them. Methods (e.g. islower()) are like functions inside the object so they do require parentheses to accept zero or more parameters and perform some work.
There are two methods for doing this. One is directly calling function by variable name using bracket and parameters and the other is by using call_user_func() Function but in both method variable name is to be used. call_user_func( $var );
With parenthesis the method is invoked because of the parenthesis, the result of that invocation will be stored in before_add. Without the parenthesis you store a reference (or "pointer" if you will) to the function in the variable. edit: Added as answer which should be more appropriate. Does this answer your question?
print is not a variable functions
Because this is a language construct and not a function, it cannot be called using variable functions
And :
Variable functions
PHP supports the concept of variable functions. This means that if a variable name has parentheses appended to it, PHP will look for a function with the same name as whatever the variable evaluates to, and will attempt to execute it. Among other things, this can be used to implement callbacks, function tables, and so forth.
Only by editing the PHP codebase and adding a new language construct.
-Adam
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With