PHP.mk документација

get_parent_class

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.get-parent-class.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека function.get-parent-class.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
get_parent_class

Референца за `function.get-parent-class.php` со подобрена типографија и навигација.

function.get-parent-class.php

get_parent_class

(PHP 4, PHP 5, PHP 7, PHP 8)

get_parent_classЈа презема името на родителската класа за објект или класа

= NULL

get_parent_class(object|string $object_or_class = ?): string|false

Ја презема името на родителската класа за објект или класа.

Параметри

object_or_class

Тестираниот објект или името на класата.

Вратени вредности

Враќа име на родителската класа на класата од која object_or_class е инстанца или името.

Ако објектот нема родител или дадената класа не постои, false ќе биде вратено.

Дневник на промени

Верзија = NULL
8.3.0 Повикување get_parent_class() без аргумент сега емитува E_DEPRECATED предупредување; претходно, повикувањето на оваа функција во рамките на класата го враќаше името на таа класа.
8.0.0 На object_or_class параметарот сега прифаќа само објекти или валидни имиња на класи.

Примери

Пример #1 Користење get_parent_class()

<?php

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

?>

Пример #1 Пример што покажува затворачка ознака што го опфаќа последниот нов ред

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

Види Исто така

  • get_class() - Враќа го името на класата на објект
  • is_subclass_of() - Проверува дали објектот ја има оваа класа како еден од своите родители или ја имплементира
  • class_parents() - Врати ги родителските класи на дадената класа

Белешки од корисници Управување со PDO конекции

yukal dot alexander at gmail dot com
пред 7 години
An output of the entire inheritance chain using closures, recursion, and OOP

class ParentClass {
    public static function getChain() {
        $chain = null;
        return $function = function($className='') use (& $chain, & $function) {
            if (empty($className))
                $className = static::class;

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

            $parent = get_parent_class($className);

            if ($parent !== false) {
                $chain .= " > {$parent}";
                return $function($parent);
            }

            return $chain;
        };
    }
}

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 {}

printf("%s\n", Sub7::getChain()());

$getChain = Sub7::getChain();
printf("%s\n", $getChain('Sub3'));

Output is:
Sub7 > Sub6 > Sub5 > Sub4 > Sub3 > Sub2 > SubChild > Child > ParentClass
Sub3 > Sub2 > SubChild > Child > ParentClass
jake на qzdesign dot co dot uk
пред 6 години
Note that from PHP 5.5 you can also use `parent::class` from within a method, e.g.

<?php
    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.
falundir на gmail dot com
пред 13 години
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
пред 14 години
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

?>
orlov0562 на gmail точка com
пред 17 години
"'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.)
rmamdaminov at gmail dot com
21 години пред
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
раду дот рендец ат инес дот ро
21 години пред
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.
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.