note 93368 added to reserved.keywords
| From: | Bob at osu1 dot php dot net | Date: | Sun, 06 Sep 2009 09:02:56 +0000 |
| Subject: | note 93368 added to reserved.keywords | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-160251@lists.php.net to get a copy of this message | ||
There are some cases when you need to use a reserved keyword or language construct as a class method
name. In this instance, there is very little chance of namespace conflicts (as the class itself acts
as a namespace). If you try to define the method the old way, you will get an unexpected token
error.
There is an unobtrusive, and very useful way to use a reserved keyword for a method name. For
example, you want to define two class methods 'list' and 'unset' (these two are
language builtins and normally not allowed for method names).
<?php
class MyClass
{
// Define MyClass::unset() with a different name, e.g. 'rm'
public function rm($arg)
{
/* code... */
}
// Define MyClass::list() with a different name, e.g. 'ls'
public function ls($arg = null)
{
/* code... */
}
// Now define a __call() method (requires PHP > 5.2.3 to take effect)
public function __call($func, $args)
{
switch ($func)
{
case 'list':
return $this->ls((isset($args[0]))? $args[0]: null);
break;
case 'unset':
return $this->rm($args[0]);
break;
default:
trigger_error("Call to undefined method ".__CLASS__."::$func()",
E_USER_ERROR);
die ();
}
}
}
?>
The only caveat is that to use the long method names, you need PHP > 5.2.3. However, a nice
feature is that if you are using an older version than 5.2.3, all of the __call() stuff is ignored
and the class will behave as expected (in other words, it degrades gracefully).
You also need to be aware of the methods' expected arguments. MyClass::ls()'s argument is
optional, so the extra isset() check is required. If your methods take more arguments, they will
need to be manually dereferenced from the $args array, e.g. <?php return
$this->my_func($args[0], $args[1], $args[2]);?> for 3 required arguments.
This is a nice trick, and can let you code better APIs for newer versions of PHP. However, if this
script is to be run on older PHP installations, be very sure to use the short method names.
----
Server IP: 117.55.229.1
Probable Submitter: 58.96.44.86
----
Manual Page -- http://www.php.net/manual/en/reserved.keywords.php
Edit -- https://master.php.net/note/edit/93368
Del: integrated -- https://master.php.net/note/delete/93368/integrated
Del: useless -- https://master.php.net/note/delete/93368/useless
Del: bad code -- https://master.php.net/note/delete/93368/bad+code
Del: spam -- https://master.php.net/note/delete/93368/spam
Del: non-english -- https://master.php.net/note/delete/93368/non-english
Del: in docs -- https://master.php.net/note/delete/93368/in+docs
Del: other reasons-- https://master.php.net/note/delete/93368
Reject -- https://master.php.net/note/reject/93368
Search -- https://master.php.net/manage/user-notes.php