3

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 Answer 1

4

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;
    }
}

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

// Edit: Based on OP's comments
$ThatObject= new ThatClass();
$ThatObject->setModel($Class);
echo $ThatObject->getModel()->getFIRST(); //returns: hey
echo $ThatObject->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

Sign up to request clarification or add additional context in comments.

6 Comments

Yes, that works, but try creating ThatClass and storing a reference to $Class in ThatClass then try access the ThisClass constants using that reference!
@Hailwood I've edited my answer based on your comments. Check it out. Works as intended on my machine. Let me know how else I can assist.
Try replacing this line $this->model = $model; with $this->model::FIRST that's the issue, I need to access it from inside the class, which is where is falls over for me.
@Hailwood I created a new function Hailwood() in ThatClass, which does your $this->model::FIRST by assigning $this->model to a variable first. Works.
Odd, I have no idea what it was then! ah well, if this works I 'spose I shall accept it!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.