Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I create a PHP function that I can call without parentheses?

Tags:

function

php

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?

like image 723
Andy Lester Avatar asked Oct 17 '08 15:10

Andy Lester


People also ask

What happens when you call a function without parentheses?

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.

Why do some methods not have parentheses?

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.

How do you write a function and call it in PHP?

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 );

What is the difference between calling function with parentheses and without in Javascript?

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?


2 Answers

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.

like image 182
Patrick Desjardins Avatar answered Sep 23 '22 08:09

Patrick Desjardins


Only by editing the PHP codebase and adding a new language construct.

-Adam

like image 45
Adam Davis Avatar answered Sep 24 '22 08:09

Adam Davis