Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get constant overridden from child in method declared within an abstract class

I have this (shortened):

abstract class MyModel
{
    const DBID = "";
    const TOKEN = "";

    public function getDB()
    {
        if(!$this->_DB)
        {
            $c = get_called_class(); // doesn't work pre php 5.3
            echo $c::DBID; // doesn't work pre php 5.3
            echo $c::TOKEN // doesn't work pre php 5.3
        }

        return $this->_qb;
    } 

The problem is that get_called_class() and the $c::DBID/TOKEN doesn't work in php < 5.3

Is there a way I can accomplish the same task from within the abstract class that is compatible with 5.2.9?

like image 288
doremi Avatar asked Feb 03 '26 06:02

doremi


1 Answers

EDIT: Constants aren't really meant to be changed throughout object instantiations, you may want to consider member variables instead.

Abstract classes cannot be instantiated directly. You could create a child class to extend your abstract class, then make the call to getDb().

abstract class MyModel
{
    private $dbId;
    private $token;

    public function setDbId($dbId)
    {
        $this->dbId = $dbId;
    }

    public function setToken($token)
    {
        $this->token = $token;
    }

    public function getDbId()
    {
        return $this->dbId;
    }

    public function getToken()
    {
        return $this->token;
    }

    public function __construct()
    {
        // All child classes will have the same values
        $this->setDbId('myParentDbId');
        $this->setToken('myParentToken');
    }

    protected function getDb()
    {
        echo $this->getDbId();
        echo $this->getToken();
    }
}

class MyChildModel extends MyModel
{
    // Don't need any methods, just access to abstract parent
    // But if I wanted to override my parent I could do this
    public function __construct()
    {            
        parent::__construct();

        $this->setDbId('myChildDbId');
        $this->setToken('myChildToken');
    }
}

$myChildModel = new MyChildModel();
var_dump($myChildModel->getDb());
like image 175
Mike Purcell Avatar answered Feb 04 '26 21:02

Mike Purcell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!