首页 > php > php获取对象类名的方法

php获取对象类名的方法

作者:bin

一、get_class,获取当前类名

class foo {
    function name()
    {
        echo "My name is " , get_class($this) , "\n";
    }
}
$bar = new foo();
echo "Its name is " , get_class($bar) , "\n";
$bar->name();

二、get_called_class,获取静态调用方法的类名

class foo {
    static public function test() {
        var_dump(get_called_class());
    }
}

class bar extends foo {
}

foo::test();
bar::test();

三、get_parent_class,获取父类类名称

class dad {
    function dad()
    {
    // implements some logic
    }
}

class child extends dad {
    function child()
    {
        echo "I'm " , get_parent_class($this) , "'s son\n";
    }
}

class child2 extends dad {
    function child2()
    {
        echo "I'm " , get_parent_class('child2') , "'s son too\n";
    }
}

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

您必须 [ 登录 ] 才能发表留言!