note 54194 added to ref.classobj
| From: | zabmilenko at hotmail dot com | Date: | Mon, 27 Jun 2005 07:08:57 +0000 |
| Subject: | note 54194 added to ref.classobj | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-90994@lists.php.net to get a copy of this message | ||
((PHP5))
I wanted to dynamically choose an extender for a class. This took awhile of playing with it but I
came up with a solution. Note that I can't verify how safe it is, but it appears to work for
me. Perhaps someone else can shed light on the details:
<?php
class A { var $value = "Class A\n"; }
class B { var $value = "Class B\n"; }
// Uncomment which extender you want. You can use variables as well.
// define('__EXTENDER__', 'A');
define('__EXTENDER__', 'B');
// Use eval to create a wrapper class.
eval('class EXTENDER extends '. __EXTENDER__ . ' { }');
class C extends EXTENDER
{
function __construct()
{
echo $this->value;
}
}
$t = new C;
?>
Outputs: Class B
Practical application: I have a database abstraction system that has individual classes for mysql,
pgsql, et al. I want to be able to create a global db class that extends one of the individual db
classes depending on the application configuration.
I know that there are probably much better ways of doing this but I haven't reached that level
when it comes to classes.
----
Manual Page -- http://www.php.net/manual/en/ref.classobj.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+54194
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+54194&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+54194&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+54194&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+54194&report=yes&reason=useless
Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+54194&report=yes&reason=non-english
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+54194&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+54194&report=yes
Search -- http://master.php.net/manage/user-notes.php