[英]PHP passing a class to another class and using a constant from it
I'm trying to use a constant from a class that I'm passing to another class, but I can't work out how to call it. 我正在尝试使用我正在传递给另一个类的类中的常量,但我无法弄清楚如何调用它。 Can anyone point out where I'm going wrong: 任何人都可以指出我出错的地方:
Class A {
const TEST = 1;
}
Class B {
protected $c;
function func($c) {
$this->c = $c;
echo $this->c::TEST; // this doesn't work
}
}
$a = new A();
$b = new B();
$b->func($a);
Accessing constants on instances on properties is only a syntactical ambiguity/incompatibility in PHP versions < 7. What you're doing work fine in versions >= 7. This works just fine in all versions: 在属性上访问实例上的常量只是PHP版本<7中的语法歧义/不兼容性。您在版本中工作正常> = 7.这在所有版本中都可以正常工作:
function func($c) {
echo $c::TEST;
}
In PHP < 7, you'll have to resort to: 在PHP <7中,您将不得不诉诸:
$c = $this->c;
$c::TEST;
Since TEST
is a constant, you access it statically, like A::TEST
由于TEST
是常量,因此您可以静态访问它,例如A::TEST
Check the PHP manual: http://php.net/manual/en/language.oop5.constants.php 查看PHP手册: http : //php.net/manual/en/language.oop5.constants.php
This only works in php 7. 这仅适用于php 7。
What you can do in PHP 5 is replace your: 您在PHP 5中可以做的是替换您的:
echo $this->c::TEST;
with: 有:
echo A::TEST;
or: 要么:
echo $c::TEST;
Class A {
const TEST = 1;
function getText()
{
return static::TEST;
}
}
then use this function (notice static keywords for Inheritance) 然后使用此函数(注意静态关键字继承)
Class B {
protected $c;
function func($c) {
$this->c = $c;
echo $this->c->getTest();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.