According to Wikipedia, prototype-based programming is “a style of object-oriented programming in which classes are not present, and behavior reuse (known as inheritance in class-based languages) is performed via a process of cloning existing objects that serve as prototypes”With magic methods, traits, and anonymous functions – this is now possible in PHP.
class SimpleXML
{
use \Prototype;
}
$SimpleXML = new SimpleXML();
$SimpleXML->load = function( $path )
{
if( file_exists( $path ))
return simplexml_load_file( $path );
return null;
};
$SimpleXML->load = function( $data )
{
return simplexml_load_string( $data );
};
The previous code uses SimpleXML and contains a class declaration by that name with a single trait that is shown later. The class is then instantiated and 2 anonymous functions are added to the prototype. With the above code and the Prototype trait, the following statements are both possible.
$doc = $SimpleXML->load( 'test.xml' );
$doc = $SimpleXML->load( 'test' );
The first method triggers the Closure that uses simplexml_load_file and the second method triggers simplexml_load_string respectively. You may notice that both functions are assigned to the same property. Using the prototype trait, it is possible to define 2 functions with the same name and number of arguments. This is a lot like traditional method overloading which was previously not possible with PHP. Overloading in this way is primitive and requires that overloaded methods meet certain criteria, namely that a given method return null if the input is not valid.
Read more »