Instance creation expression in PHP4

at 2005-07-17 in Editorial by friebe (0 comments)

The instance creation expression lets you create anonymous classes using the following form:

new ClassOrInterfaceType (ArgumentListopt) { ClassBody }

Supplying a ClassBody is available in PHP5 when using our patch to it, but not in PHP4. This article shows a way to simulate it.

Let's look at a small example first:

<?php 
$list->sort(new Comparator() {
public
function compare($a, $b) {
return strnatcmp
($a, $b);
}
});
?>

If the name specified after the keyword "new" refers to a class, the class being instantiated will extend this class. In case it refers to an interface, the specified interface will be implemented by the class being instantiated.

The implementation in PHP4:
As we cannot extend the syntax in userland, we'll have to go for a trick - defining the sourcecode within a string and using eval() will do what we want.

PHP4 version of above example:
<?php 
$list->sort(newinstance('Comparator', '{
function compare($a, $b) {
return strnatcmp($a, $b);
}
}'
));
?>

The newinstance() function will take two arguments:
  • The class or interface name (unqualified)
  • The sourcecode, "enclosed" by curly braces

The function then checks for whether the passed class or interface name is an interface (in XP for PHP4, that is the case when the class extends Interface - see here for more details) and generates sourcecode depending on that, passing it to eval(). It then creates an instance by using the dynamic class name instantiation (new $name()) and returns it.

See here for the complete sourcecode.

Note: This is not an RFC for new core functionality - I am undecided whether this would be a good addition. If you think it is, well: Go ahead and create an RFC:)



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

Related

Find related articles by a search for «Instance».