user3210615 user3210615 - 4 years ago 110
PHP Question

Calling __construct from child class statically(?)

I have the following php code:

<?php

class ParentClass {

public $table_name;

function __construct() {
$this->table_name = strtolower(__CLASS__);
}

}

class ChildClass extends ParentClass {

function __construct() {
parent::__construct();
//And I also want to put here other codes
}

}

$parent = new ParentClass();
$child = new ChildClass();

echo $parent->table_name . "<br />" . $child->table_name;

?>


the result is

parentclass
parentclass


however I want it to be

parentclass
childclass


How do I achieve it?
Late static binding would solve my problem, however it cant be called statically of course.
http://php.net/manual/en/language.oop5.late-static-bindings.php

Answer Source

This works in PHP5.5 and upwards:

class ParentClass 
{
    public $table_name;

    public function __construct() 
    {
        $this->table_name = strtolower(static::class);
    }
}

class ChildClass extends ParentClass 
{
    public function __construct() 
    {
        parent::__construct();     
        // ...
    }
}

$parent = new ParentClass();
$child = new ChildClass();

echo $parent->table_name . "<br />" . $child->table_name;

For reference, see http://php.net/manual/en/language.oop5.basic.php#language.oop5.basic.class.class.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download