note 77391 deleted from language.oop by danbrown
| From: | danbrown@php.net | Date: | Sat, 07 Nov 2009 19:03:00 +0000 |
| Subject: | note 77391 deleted from language.oop by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-162553@lists.php.net to get a copy of this message | ||
Note Submitter: Aouie Web_Form_Aouie.net
----
class casting (type casting to an extended class) workaround. Useful to use functionality in an
extended class on an instance of a base class (especially when the BaseClass file needs to be small
and the extended class functions are huge). Tested to work on public, protected and private vars in
PHP5.
---
class ABaseClass
{
private $T1;
protected $T2;
public $T3;
public function CopyFrom( )
{
// If this class had parents then you will want to implement and use parent::$CopyFrom( ). If
not, then private members in the parent class will not be copied.
return get_object_vars( $this );
}
protected function CopyInto( $VarArr )
{
// If this class had parents then in order to copy the private values we must implement and use
parent::CopyInto( $VarArr ).
$TempArr = get_class_vars( __CLASS__ );
foreach( $TempArr as $VarName => $Var1 )
{
$this->$VarName = $VarArr[ $VarName ];
}
}
}
class AnExtendedClass extends ABaseClass
{
public function __construct( $theBaseClassInstance )
{
$this->CopyInto( $theBaseClassInstance->CopyFrom( ) );
}
public function LongFunctionIntheFileWithTheExtendedClass( )
{
// Bla Bla Bla
}
}
---
$BaseInstance = new ABaseClass();
...
$ExtendedInstance = new AnExtendedClass( $BaseInstance );
$ExtendedInstance->LongFunctionIntheFileWithTheExtendedClass( );