Php get object parents

get_parent_class

The tested object or class name. This parameter is optional if called from the object’s method.

Return Values

Returns the name of the parent class of the class of which object_or_class is an instance or the name.

Note:

If the object does not have a parent or the class given does not exist false will be returned.

If called without parameter outside object, this function returns false .

Changelog

Version Description
8.0.0 The object_or_class parameter now only accepts objects or valid class names.

Examples

Example #1 Using get_parent_class()

class Dad function __construct ()
// implements some logic
>
>

class Child extends Dad function __construct ()
echo «I’m » , get_parent_class ( $this ) , «‘s son\n» ;
>
>

class Child2 extends Dad function __construct ()
echo «I’m » , get_parent_class ( ‘child2’ ) , «‘s son too\n» ;
>
>

$foo = new child ();
$bar = new child2 ();

The above example will output:

I'm Dad's son I'm Dad's son too

See Also

  • get_class() — Returns the name of the class of an object
  • is_subclass_of() — Checks if the object has this class as one of its parents or implements it
  • class_parents() — Return the parent classes of the given class

User Contributed Notes 7 notes

An output of the entire inheritance chain using closures, recursion, and OOP

if (empty($chain))
$chain = $className;

if ($parent !== false) $chain .= » > «;
return $function($parent);
>

class Child extends ParentClass <>
class SubChild extends Child <>
class Sub2 extends SubChild <>
class Sub3 extends Sub2 <>
class Sub4 extends Sub3 <>
class Sub5 extends Sub4 <>
class Sub6 extends Sub5 <>
class Sub7 extends Sub6 <>

$getChain = Sub7::getChain();
printf(«%s\n», $getChain(‘Sub3’));

Output is:
Sub7 > Sub6 > Sub5 > Sub4 > Sub3 > Sub2 > SubChild > Child > ParentClass
Sub3 > Sub2 > SubChild > Child > ParentClass

You can use this function to find common parent of multiple objects or classes.

/**
* 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 ;
>

Читайте также:  Get java path cmd

$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:

//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’ ));
?>

I wrote a simple function doing the reverse thing: get the children:

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__ );
>
>

$c = new C ();
echo $c -> someFunction (); //displays B

PHP (4 at least, dunno about 5) stores classnames in lower case, so:

echo get_parent_class ( ‘Bar’ );

echo get_parent_class ( ‘bar’ );

Источник

get_parent_class

The tested object or class name. This parameter is optional if called from the object’s method.

Return Values

Returns the name of the parent class of the class of which object_or_class is an instance or the name.

Note:

If the object does not have a parent or the class given does not exist false will be returned.

If called without parameter outside object, this function returns false .

Changelog

Version Description
8.0.0 The object_or_class parameter now only accepts objects or valid class names.

Examples

Example #1 Using get_parent_class()

class Dad function __construct ()
// implements some logic
>
>

class Child extends Dad function __construct ()
echo «I’m » , get_parent_class ( $this ) , «‘s son\n» ;
>
>

class Child2 extends Dad function __construct ()
echo «I’m » , get_parent_class ( ‘child2’ ) , «‘s son too\n» ;
>
>

$foo = new child ();
$bar = new child2 ();

The above example will output:

I'm Dad's son I'm Dad's son too

See Also

  • get_class() — Returns the name of the class of an object
  • is_subclass_of() — Checks if the object has this class as one of its parents or implements it
  • class_parents() — Return the parent classes of the given class

User Contributed Notes 7 notes

An output of the entire inheritance chain using closures, recursion, and OOP

if (empty($chain))
$chain = $className;

if ($parent !== false) $chain .= » > «;
return $function($parent);
>

class Child extends ParentClass <>
class SubChild extends Child <>
class Sub2 extends SubChild <>
class Sub3 extends Sub2 <>
class Sub4 extends Sub3 <>
class Sub5 extends Sub4 <>
class Sub6 extends Sub5 <>
class Sub7 extends Sub6 <>

Читайте также:  Count char in string in php

$getChain = Sub7::getChain();
printf(«%s\n», $getChain(‘Sub3’));

Output is:
Sub7 > Sub6 > Sub5 > Sub4 > Sub3 > Sub2 > SubChild > Child > ParentClass
Sub3 > Sub2 > SubChild > Child > ParentClass

Note that from PHP 5.5 you can also use `parent::class` from within a method, e.g.

function child ()
echo «I’m » , parent ::class, «‘s son\n» ;
>
?>

Looks a bit tidier and technically probably more optimal, as it avoids a function call lookup.

I wrote a simple function doing the reverse thing: get the children:

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__ );
>
>

$c = new C ();
echo $c -> someFunction (); //displays B

PHP (4 at least, dunno about 5) stores classnames in lower case, so:

echo get_parent_class ( ‘Bar’ );

echo get_parent_class ( ‘bar’ );

You can use this function to find common parent of multiple objects or classes.

/**
* 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:

//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’ ));
?>

«‘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.)

Читайте также:  Casting boolean to boolean java

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.

  • Classes/Object Functions
    • class_​alias
    • class_​exists
    • enum_​exists
    • get_​called_​class
    • get_​class_​methods
    • get_​class_​vars
    • get_​class
    • get_​declared_​classes
    • get_​declared_​interfaces
    • get_​declared_​traits
    • get_​mangled_​object_​vars
    • get_​object_​vars
    • get_​parent_​class
    • interface_​exists
    • is_​a
    • is_​subclass_​of
    • method_​exists
    • property_​exists
    • trait_​exists
    • _​_​autoload

    Источник

    ReflectionClass::getParentClass

    A ReflectionClass or false if there’s no parent.

    See Also

    User Contributed Notes 3 notes

    Quick correction, the code for getting all parent classes below has a «typo», you need to reset the $class variable to the parent class instance, otherwise it just endlessly loops:

    $class = new ReflectionClass(‘classname’);

    while ($parent = $class->getParentClass()) $parents[] = $parent->getName();
    $class = $parent;
    >

    echo «Parents: » . implode(«, «, $parents);

    Here is a «replacement» for is_a that will additionally look both into the extended classes and in the implemented interfaces

    /**
    * Check if a class extends or implements a specific class/interface
    * @param string $search The class or interface name to look for
    * @param string $className The class name of the object to compare to
    * @return bool
    */
    function IsExtendsOrImplements ( $search , $className ) <
    $class = new ReflectionClass ( $className );
    if( false === $class ) <
    return false ;
    >
    do <
    $name = $class -> getName ();
    if( $search == $name ) <
    return true ;
    >
    $interfaces = $class -> getInterfaceNames ();
    if( is_array ( $interfaces ) && in_array ( $search , $interfaces )) <
    return true ;
    >
    $class = $class -> getParentClass ();
    > while( false !== $class );
    return false ;
    >
    ?>

    When you want to find all parents (parent, parent of parent, parent of parent’s parent and so on) try:

    $class = new ReflectionClass ( ‘whatever’ );

    while ( $parent = $class -> getParentClass ()) $parents [] = $parent -> getName ();
    >

    echo «Parents: » . implode ( «, » , $parents );
    ?>

    ReflectionClass::getParentClass() can return a ReflectionClass object of the parent class or false if no parent.

    • ReflectionClass
      • _​_​construct
      • getAttributes
      • getConstant
      • getConstants
      • getConstructor
      • getDefaultProperties
      • getDocComment
      • getEndLine
      • getExtension
      • getExtensionName
      • getFileName
      • getInterfaceNames
      • getInterfaces
      • getMethod
      • getMethods
      • getModifiers
      • getName
      • getNamespaceName
      • getParentClass
      • getProperties
      • getProperty
      • getReflectionConstant
      • getReflectionConstants
      • getShortName
      • getStartLine
      • getStaticProperties
      • getStaticPropertyValue
      • getTraitAliases
      • getTraitNames
      • getTraits
      • hasConstant
      • hasMethod
      • hasProperty
      • implementsInterface
      • inNamespace
      • isAbstract
      • isAnonymous
      • isCloneable
      • isEnum
      • isFinal
      • isInstance
      • isInstantiable
      • isInterface
      • isInternal
      • isIterable
      • isIterateable
      • isReadOnly
      • isSubclassOf
      • isTrait
      • isUserDefined
      • newInstance
      • newInstanceArgs
      • newInstanceWithoutConstructor
      • setStaticPropertyValue
      • _​_​toString
      • export

      Источник

Оцените статью