Re: extending a class?

From: Date: Tue, 26 Feb 2002 11:31:40 +0000
Subject: Re: extending a class?
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-86225@lists.php.net to get a copy of this message
Nick Wilson wrote:
So I was thinking: $form=new form('dk') Would extend the class to include all the dk language routines and $form=new form('en') Would do likewise for english. You can do this with encapsulation. Your "form" object would actually be a wrapper around an encapsulated object which does all of the actual work. When you call the constructer it specifies which object is encapsulated by the wrapper. For example:
class FormBase { // Contains any methods shared by both formDK and formEN } class FormDK extends FormBase { // The class for DK language support } class FormEN extends FormBase { // The class for EN language support } class Form { var $formObject; function form($language) {
       if ($language == 'dk') {
           $this->formObject = new FormDK;
       } else {
           $this->formObject = new FormEN;
       }
} // The other methods in this class simply "pass through" to $this->formObject - e.g function doSomething($variable) {
       return $this->formObject->doSomething($variable);
} } Another different of doing the same kind of thing would be to use an "object factory" as seen in the PEAR DB abstraction layer. This works by having a static class method (i.e a method that can be called without creating an instance of the class first) which returns a different object depending on what arguments you use. Here is an example (it expects FormEN and FormDK to have been defined as above): class Form { function getFormObject($language) {
       if ($language == 'dk') {
           return new FormDK;
       } else {
           return new FormEN;
       }
} You can now create you object with the following code: $form = Form::getFormObject('en'); or $form = Form::getFormObject('dk'); <disclaimer: I haven't tested any of the above code but the principles should be sound> Cheers, Simon Willison

« previous php.general (#86225) next »