Accessing class constants from instance stored in another class

匆匆过客 提交于 2020-01-13 20:34:06

问题


I have a class defined which has several constants defined through `const FIRST = 'something';

I have instantiated the class as $class = new MyClass()

then I have another class that takes a MyClass instance as one of it's constructors parameters and stores it as $this->model = $myClassInstance;

This works fine.

But I am wondering how I can access the constants from that instance?

I tried case $this->model::STATE_PROCESSING but my IDE tells me

Incorrect access to static class member.

and PHP tells me

unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM) in ...

I know I can do MyClass::STATE_PROCESSING but I am wondering if there is a way to get them based off the instance?


回答1:


Seems like your on an older version of php? PHP 5.3 allows the access of constants in the manner you describe... However, this is how you can do it without that inherent ability:

class ThisClass
{
    const FIRST = 'hey';

    public function getFIRST()
    {
        return self::FIRST;
    }
}

class ThatClass
{
    private $model;

    public function setModel(ThisClass $model)
    {
        $this->model = $model;
    }

    public function getModel()
    {
        return $this->model;
    }

    public function Hailwood()
    {
        $test = $this->model;
        return $test::FIRST;
    }
}

$Class = new ThisClass();
echo $Class->getFIRST(); //returns: hey
echo $Class::FIRST; //returns: hey; PHP >= 5.3

// Edit: Based on OP's comments
$Class2 = new ThatClass();
$Class2->setModel($Class);
echo $Class2->getModel()->getFIRST(); //returns: hey
echo $Class2->Hailwood(); //returns: hey

Basically, were creating a 'getter' function to access the constant. The same way you would to externally access private variables.

See the OOP Class Constants Docs: http://php.net/manual/en/language.oop5.constants.php



来源:https://stackoverflow.com/questions/13638014/accessing-class-constants-from-instance-stored-in-another-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!