note 48641 added to ref.classobj
| From: | covertkaatmuohiodotedu at osu1 dot php dot net | Date: | Mon, 03 Jan 2005 01:27:04 +0000 |
| Subject: | note 48641 added to ref.classobj | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-82627@lists.php.net to get a copy of this message | ||
To pillepop2003 at yahoo dot de:
I have the same issue. I have a base class that manages database tasks for a number of child
classes. One of the functions in the base class is a find() method that returns instances of the
child classes. Since find() is usually called as a static method, it needs to know the name of the
child class. As you've found, this appears to be impossible to get in an easy fashion.
The only way I've found to get the child class name is to use the debug_traceback() function.
This requires me to have a find() method in every child class, but it does work.
Here's an example:
<?php
require_once("Application.php");
class parentClass {
function find() {
$className = NULL;
foreach (debug_backtrace() as $bt) {
if ($bt['function'] == __FUNCTION__) {
$className = $bt['class'];
}
}
// here should be some code to find the proper id, let's assume it was id 1
$id = 1;
return new $className($id);
}
}
class foo extends parentClass {
function __construct($id) {
$this->id = id;
}
function find() {
return parent::find();
}
}
class bar extends parentClass {
function __construct($id) {
$this->id = id;
}
function find() {
return parent::find();
}
}
$a = foo::find();
printf("Type for \$a: %s<br/>\n", get_class($a));
$b = bar::find();
printf("Type for \$b: %s<br/>\n", get_class($b));
?>
----
Manual Page -- http://www.php.net/manual/en/ref.classobj.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+48641
Delete -- http://master.php.net/manage/user-notes.php?action=delete+48641&report=yes
Reason: bad code -- http://master.php.net/manage/user-notes.php?action=delete+48641&report=yes&reason=bad+code
Reason: spam -- http://master.php.net/manage/user-notes.php?action=delete+48641&report=yes&reason=spam
Reason: useless example -- http://master.php.net/manage/user-notes.php?action=delete+48641&report=yes&reason=useless+example
Reason: contains commercial links -- http://master.php.net/manage/user-notes.php?action=delete+48641&report=yes&reason=contains+commercial+links
Reason: useless note -- http://master.php.net/manage/user-notes.php?action=delete+48641&report=yes&reason=useless+note
Reject -- http://master.php.net/manage/user-notes.php?action=reject+48641&report=yes
Search -- http://master.php.net/manage/user-notes.php