Matt Asbury
Matt Asbury

Reputation: 5662

Determine the child class that has used parent::__construct();

I have a situation where I need to pass the name of the child class back to the parent class in order to take some action.

The way I have it set up at the moment is:

class SomeParentClass {

    public function __construct($c = false){
        ...
    }

}

class SomeChildClass extends SomeParentClass {

    public function __construct(){
        parent::__construct(__CLASS__){
            ...
        }
    }

}

This will pass the name of the child class back to the parent, but if the child class does not do this then the variable $c will retain the bool value false.

It works, it makes sense, but is this the cleanest way to do this? Is there a way to auto detect which child class has called parent::__construct() without passing it as a variable?

Many thanks

Upvotes: 0

Views: 208

Answers (3)

Ja͢ck
Ja͢ck

Reputation: 173642

I could be wrong, but under normal circumstances, the parent shouldn't be aware of its child classes. I'm sure there's a better way to do what you're trying to do.

Exceptions to this "rule" is perhaps base classes that expose static (optionally final) constructors which are then called with a child class prefixed, e.g.

class Parent
{
    public final static function create()
    {
        return new static;
    }
}

class Child extends Parent
{
    public function __construct()
    {
        // special code here
    }
}

var_dump(Child::create());

Upvotes: 1

gunnx
gunnx

Reputation: 1209

<?php
class SomeParentClass {

    public function __construct($c = false){       
        echo get_called_class();
    }

}

class SomeChildClass extends SomeParentClass {

    public function __construct(){
        parent::__construct(__CLASS__);       
    }

}

class OtherChildClass extends SomeParentClass {
    public function __construct(){
        parent::__construct(__CLASS__);  
    }

}

$a = new SomeChildClass();
$b = new OtherChildClass();

Upvotes: 2

luxcem
luxcem

Reputation: 1854

You can do this with get_called_class() ( http://php.net/manual/en/function.get-called-class.php ) in PHP 5.

See : Getting the name of a child class in the parent class (static context)

Upvotes: 2

Related Questions