I have implemented two classes, isbn10 and isbn13. I would like to create a class isbn so that when instantiated I will obtain an object of type isbn10 or isbn13, according to a parameter given to the isbn class constructor:
$isbn_code = new isbn('978-3-16-148410-0');
I know I could do something like this with a static method:
class isbn {
public static function new($isbn) {
if (preg_match('/' . isbn13::isbn_regex . '/', $isbn)) {
return new isbn13($isbn);
} else if (preg_match('/' . isbn10::isbn_regex . '/', $isbn)) {
return new isbn10($isbn);
} else {
throw new Exception("Invalid ISBN code", 1);
}
}
}
$isbn_code = isbn::new('978-3-16-148410-0');
But would it be possible to instantiate the isbn class and automatically obtain a isbn13 object (or isbn10)?
No. Using a static ‘factory’ method, such as you have described, is the way to properly do this. In strongly typed languages this can be better handled, but not in PHP. This is because constructors do not return the object, they just create it.