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

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?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

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.

Solution 2

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

-Adam

Solution 3

No, you can’t do that in PHP.
Print isn’t actually a function, it’s a “language construct”.

Solution 4

Nope, PHP won’t allow you to do that.

Solution 5

I was looking for a way to code a echoh to do something like:

echoh "hello";

and get:

'hello<br>\n'.

I guess one solution could be defining a constant and use it:

<?php
const PHP_BR_EOL = "<br>\n";
echo "Hello" . PHP_BR_EOL;
?>

Now I get:

Hello<br>

I know it requires more typing, but it is more complient with the examples on the PHP manual, and I use gvim with omnicomplete to save on the typing. Also it would be easy to do a global search/replace PHP_EOL by PHP_BR_EOL.

Solution 6

That can’t be done with PHP. Functions you declare must be called with brackets.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply