Accessing class constants from instance stored in another class
class, object, oop, php, static
Solution
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
Problem
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?