Getting the name of a child class in PHP

前端 未结 3 885
借酒劲吻你
借酒劲吻你 2020-12-22 02:12

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, <

3条回答
  •  不知归路
    2020-12-22 03:01

    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

提交回复
热议问题