PHP class method called print ... not allowed?

I am writing a controller for Codeigniter using the "print" method. The name is important because I would like to have access to the page at http://www.mysite.com/mycontroller/print . "

However, I cannot do this because there is a syntax error:

Parse error: syntax error, unexpected T_PRINT, expecting T_STRING 

Is there any special syntax for the PHP interpreter to β€œthink” when I say:

 class MyClass extends Controller { function print() { // print method here } } 

... what am I talking about a method called T_STRING "print", not the T_PRINT that it expects?

+4
source share
6 answers

This will not work, because print is a language construct in php. I know this looks like a function, but is handled in the same way as (for example) function , while , include , etc.

+10
source

See the Reserved Keywords list in PHP . You cannot use them as constants, class names, function or method names.

+4
source

I found that you can bypass the name restriction for some reserved words in PHP 5.3 using the magic __call method.

 public function __call( $name, $arguments ) { $fn = 'do_' . $name; if ( method_exists( $this, $fn ) ) { return call_user_func_array( array( $this, fn), $arguments ); } else { throw new Exception( 'Method "' . $name . '" does not exist.' ); } } protected function do_print( /* $arg1, $arg2,...*/ ) { //whatever } 

I'm not saying this is necessarily a good idea, but it allows you to make a call like $foo->print() .

I really see no reason why reserved words cannot be used as method names for classes. I could not come up with an ambiguous case that would have to be resolved.

+4
source

print as echo or isset are language constructs and cannot be used as functions or class names.

+2
source

If you called the print function "hardcopy ()", for example, you could use the mod-rewrite rule to do the same. those.:

RewriteRule ^ / mycontroller / print / mycontroller / hardcopy [L]

+2
source

As everyone noted, you cannot use language constructs as function names.

Your solution is probably routing a URI so you can use print in your url, but something safe like the name of your method.

+2
source

Source: https://habr.com/ru/post/1303261/


All Articles