Getting the name of a child class in PHP

2019-01-29 06:32发布

Lets say I'm building a base class which will be extended upon by the children class. So a base class is called Base and children can be Child1, Child2, etc.

In the base class's constructor, how can i get the value of Child1/Child2?

This is all using PHP

标签: php oop
3条回答
冷血范
2楼-- · 2019-01-29 06:56

A base class should really never depend on information about child classes---

To answer your question:

class base {
    public function __construct() {
        print "Class:" . get_class($this) . "\n";
    }
}

class child extends base{
    public function __construct() {
        parent::__construct();
    }
}
$c = new child();

Just for future reference -- this can be acheived in a static context using get_called_class(), but this is only available in PHP >= 5.3

查看更多
闹够了就滚
3楼-- · 2019-01-29 07:00

simply call get_class($this) - note however that a base class method has no real business in changing its behaviour depending on which derived class is using it. That's the whole point of deriving a class :)

查看更多
Animai°情兽
4楼-- · 2019-01-29 07:17

Edit: Didn't know about get_class, disregard this one ;)

You could try __CLASS__ but it might not work properly.

A work-around could be to specify the class name as a property of the base class.

Edit: This does not work (I used the following code) construct() { echo __CLASS; } }

class b extends a {}

$b = new b;

I would suggest passing the name of $b as a parameter to A, for example:

<?php
class a {
    protected $name;
    public function __construct() {
        echo $this->name;
    }
}

class b extends a {
    protected $name = __CLASS__;
}

$b = new b;
查看更多
登录 后发表回答