开发者

PHP class method named print... not allowed?

I am writing a Controller for Codeigniter with a method named "print". The name is important, because I would like to be able to access the page at "http://www.mysite.com/mycontroller/print".

Howev开发者_开发百科er, I cannot do this because there is the syntax error:

Parse error: syntax error, unexpected T_PRINT, expecting T_STRING

Is there any special syntax to make the PHP interpreter "think" that when I say:

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

... that I am talking about a method with a T_STRING name of "print" and not the T_PRINT that it is expecting it to be?


This won't work because print is a language construct in php. I know it looks like a function, but it is treated the same way as (for example) function, while, include, and so on.


I found that you can get around the naming restriction for some reserved words in PHP 5.3 using the __call magic 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 does allow you to make a call like $foo->print().

I really see no reason why reserved words can't be used as method names for classes. I haven't been able to come up with an ambiguous case that would need to be solved.


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


print like echo or isset are language constructs and can not be used as function or classnames.


If you called the print function 'hardcopy()' for example, you could use a mod-rewrite rule to accomplish the same thing. ie:

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


As everyone has pointed out, you can't use language constructs as function names.

Your solution is probably URI Routing so that you can use print in your url but something safe as your method name.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜