Why I can’t call a constant from class B via dynamic property of class A like this? Am I doing something wrong?
class A {
public $class_b;
}
class B {
const CONST_VAR = 'b';
}
$class_a = new A();
$class_a->class_b = new B();
echo $class_a->class_b::CONST_VAR;
PHP Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM, expecting ‘,’ or ‘;’ in /root/1.php on line 14
However calling it like this is fine:
$b = $class_a->class_b;
echo $b::CONST_VAR;
Class constants are static. You have an instance of class B in the $class_b variable so you shouldn’t access it through class A unless you make a non-static function in class B that returns the constant. For example:
Now you can use:
But there is really no reason to do it this way unless you plan on overloading class b because you can just use B::CONST_VAR;
Read about class constants here: http://php.net/manual/en/language.oop5.constants.php
It should be noted that as of php 5.3.0 constants can be accessed through instances such as you suggested, $b::CONST_VAR, but this is not how constants should be used and was most likely only added to support bad programming.