New core functionality "newinstance"

at 2006-11-29 in RFCsAnnouncementsHomepage by friebe (0 comments)

Now that RFC 0080: Anonymous class creation has been implemented, here's an overview of what can be changed for the better by using the newinstance() core functionality.

In unittests there's often the one-time need for mock objects implementing a certain interface or extending a certain base class. To date, this was accomplished by using the ClassLoader's defineClass() method. Here's an example:

  $cl= &ClassLoader::getDefault();
$class= &$cl->defineClass('net.xp_framework.unittest.util.StringCaseComparator', '
class StringCaseComparator extends Object {
function compare($a, $b) {
return strcasecmp($a, $b);
}
} implements("StringCaseComparator.class.php", "util.Comparator");
'
);
$instance= &$class->newInstance();

This can now be rewritten as follows:
  $instance= &newinstance('util.Comparator', array(), '{
function compare($a, $b) {
return strcasecmp($a, $b);
}
}'
));

First of all, this is less to type (and programmers like to type less:)), and second this could - if one day we'd be using some version of PHP (or another language) which supports this natively - migrate these cases to:
  $instance= new util.Comparator() {
function compare($a, $b) {
return strcasecmp
($a, $b);
}
};



Subscribe

You can subscribe to the XP framework's news by using RSS syndication.


Categories

News
General
PHP5
Announcements
RFCs
Further reading
Examples
Editorial
EASC
Experiments
Unittests
Databases
5.8-SERIES
Unicode
Language
5.9-SERIES

Related

Find related articles by a search for «New».