This little snippet to get the inheritance tree might be useful to someone.
<?php
header("Content-Type: text/plain;");
class Top {
public function getParents($class=null, $plist=array()) {
$class = $class ? $class : $this;
$parent = get_parent_class($class);
if($parent) {
$plist[] = $parent;
/*Do not use $this. Use 'self' here instead, or you
* will get an infinite loop. */
$plist = self::getParents($parent, $plist);
}
return $plist;
}
}
class Middle extends Top {
}
class Bottom extends Middle {
}
$o = new Bottom();
print_r($o->getParents());
?>
get_parent_class
(PHP 4, PHP 5)
get_parent_class — Recupera el nombre de la clase padre de un objeto o clase
Descripción
Recupera el nombre de la clase padre de un objeto o clase.
Parámetros
-
object -
El objeto evaluádo o nombre de la clase
Valores devueltos
Devuelve el nombre de la clase padre de la clase de la cuál
object es una instancia o el nombre.
Nota:
Si el objeto no tiene padre o la clase dada no existe devolverá
FALSE.
Si se llama sin parámetro fuera del objeto, esta función devolverá FALSE.
Historial de cambios
| Versión | Descripción |
|---|---|
| 5.1.0 |
Si se llamaba sin parámetro fuera del objeto, está función devolvía
NULL con una advertencia, pero ahora devuelve FALSE.
|
| 5.0.0 |
El parámetro object es opcional si se llama
desde el método del objeto.
|
| 4.0.5 |
Si object es una cadena devuelve el nombre de la
clase padre de la clase con ese nombre.
|
Ejemplos
Ejemplo #1 Usar get_parent_class()
<?php
class papá {
function papá()
{
// implementar algo lógico
}
}
class hijo extends papá {
function hijo()
{
echo "Soy hijo de " , get_parent_class($this) , "\n";
}
}
class hijo2 extends papá {
function hijo2()
{
echo "Yo también soy hijo de " , get_parent_class('hijo2') , "\n";
}
}
$foo = new hijo();
$bar = new hijo2();
?>
El resultado del ejemplo sería:
I'm dad's son I'm dad's son too
Ver también
- get_class() - Devuelve el nombre de la clase de un objeto
- is_subclass_of() - Verifica si el objeto tiene esta clase como uno de sus padres
michael at getsprink dot -- com ¶
4 years ago
falundir at gmail dot com ¶
1 year ago
You can use this function to find common parent of multiple objects or classes.
<?php
/**
* Returns name of the first (in class hierarchy) common parent class of all provided objects or classes.
* Returns FALSE when common class is not found.
*
* @param mixed $objects Array that can contain objects or class names.
* @return mixed
*/
function get_first_common_parent($objects) {
$common_ancestors = null;
foreach($objects as $object) {
if (is_object($object)) {
$class_name = get_class($object);
} else {
$class_name = $object;
}
$parent_class_names = array();
$parent_class_name = $class_name;
do {
$parent_class_names[] = $parent_class_name;
} while($parent_class_name = get_parent_class($parent_class_name));
if ($common_ancestors === null) {
$common_ancestors = $parent_class_names;
} else {
$common_ancestors = array_intersect($common_ancestors, $parent_class_names);
}
}
return reset($common_ancestors);
}
?>
Example:
<?php
class A {
}
class B extends A {
}
class D extends B {
}
class E extends B {
}
class C extends A {
}
class F extends C {
}
class G extends F {
}
class H {
}
//returns "A"
get_first_common_parent(array('G', 'E'));
//returns "F"
get_first_common_parent(array(new G(), 'F'));
//returns false (no common parent)
get_first_common_parent(array('C', 'H'));
//returns false (non-existent class provided)
get_first_common_parent(array(new B(), 'X'));
?>
levu ¶
2 years ago
I wrote a simple function doing the reverse thing: get the children:
<?php
function get_child($instance, $classname) {
$class = $classname;
$t = get_class($instance);
while (($p = get_parent_class($t)) !== false) {
if ($p == $class) {
return $t;
}
$t = $p;
}
return false;
}
abstract class A {
function someFunction() {
return get_child($this, __CLASS__);
}
}
class B extends A {
}
class C extends B {
}
$c = new C();
echo $c->someFunction(); //displays B
?>
ssb45 at cornell dot edu ¶
5 years ago
"'If called without parameter outside object' What on earth does that mean?"
There are two places this could be called:
1. From within a member function of an object. In this case, it may be called with no parameters and will return the parent class of the object owning the member function. (If the parameter is included, then it will return the parent class of the specified class as normal.)
2. From outside an object (i.e., global or function scope). In this case, PHP doesn't know what class you're talking about if you don't include a parameter, so it returns FALSE. (But, of course, it works if you specify the class with the parameter.)
marcus at synchromedia dot co dot uk ¶
5 years ago
"If called without parameter outside object" What on earth does that mean?
What I can tell you, and that is not documented, is that if the object in question does not have an explicitly declared parent class, it does return boolean false. It doesn't for example return 'stdClass' on the basis that all objects are derived from that.
birkholz at web dot de ¶
7 years ago
tim at correctclick dot com wrote:
<quote>
A slightly more cryptic but faster get_ancestors function:
<?php
function get_ancestors ($class) {
for ($classes[] = $class; $class = get_parent_class ($class); $classes[] = $class);
return $classes;
}
?>
(The second part of the for is implicitly testing for $class != ""). Recursion is considerably slower than looping, so you probably want to use this function.
Hope someone finds it useful.
</quote>
I would prefer this version, because it will create no duplicates:
<?php
function get_ancestors ($class) {
$classes = array($class);
while($class = get_parent_class($class)) { $classes[] = $class; }
return $classes;
}
Greets, Dennis
?>
matt-php at DONT-SPAM-ME dot bitdifferent dot com ¶
8 years ago
PHP (4 at least, dunno about 5) stores classnames in lower case, so:
<?PHP
class Foo
{
}
class Bar extends Foo
{
}
echo get_parent_class('Bar');
echo "\n";
echo get_parent_class('bar');
?>
will output:
foo
foo
radu dot rendec at ines dot ro ¶
9 years ago
If the argument obj is a string and the class is not defined, then the function returns FALSE.
If the argument obj is an object created from a class with no ancestors (or a string representing a class with no ancestors), then the function returns FALSE.
tim at correctclick dot com ¶
10 years ago
A slightly more cryptic but faster get_ancestors function:
function get_ancestors ($class) {
for ($classes[] = $class; $class = get_parent_class ($class); $classes[] = $class);
return $classes;
}
(The second part of the for is implicitly testing for $class != ""). Recursion is considerably slower than looping, so you probably want to use this function.
Hope someone finds it useful.
eric dot brison at anakeen dot com ¶
11 years ago
To return all ancestors class of an object
function get_ancestors_class($classname) {
$father = get_parent_class($classname);
if ($father != "") {
$ancestors = get_ancestors_class($father);
$ancestors[] = $father;
}
return $ancestors;
}
example :
-----------
Class C {
}
Class B extends C {
}
Class A extends B {
}
print_r (get_ancestors_class("a"));
print_r (get_ancestors_class("b"));
example result :
---------------
Array
(
[0] => c
[1] => b
)
Array
(
[0] => c
)
Michael Torp Kaalund ¶
2 years ago
I have been playing with parent and child class, and I used this function to determine that which one was calling an function. I for an example it if you only want your parent class to be able to make an function call:
here is my example (by the way this example was inspired by another example fund on php.net):
<?php
class Parents {
public static $status; //This is the status
protected static $idCount;
protected $id;
function __construct() {
$this->id = ++self::$idCount;
self::$status = "tmp";
}
public function run($task) {
if(get_parent_class($this) == "") {
echo 'Command issued: '.$task.'<br>';
self::$status = $task;
}
}
public function __tostring() {
return "(".__class__.")id=".$this->id." status=".self::$status."<br>";
}
}
class Child extends Parents {
function __construct() {
parent::__construct();
self::$status = "tmp";
echo "Child construct<br>";
}
public function __tostring() {
return "(".__class__.")id=".$this->id." status=".self::$status."<br>";
}
}
$parent = new Parents();
echo $parent;
$child = new Child();
echo $child;
echo get_parent_class('Child')."<br>";
$parent->run("mtk");
echo $parent;
echo $child;
$child->run("mtk1");
echo $parent;
echo $child;
?>
which will produces somethink like:
(Parents)id=1 status=tmp
Child construct
(Child)id=2 status=tmp
Parents
Command issued: mtk
(Parents)id=1 status=mtk
(Child)id=2 status=mtk
(Parents)id=1 status=mtk
(Child)id=2 status=mtk
hopes it helps some one :D
