Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
992 views
in Technique[技术] by (71.8m points)

oop - Accessing PHP Class Constants

The PHP manual says

Like static members, constant values can not be accessed from an instance of the object.

which explains why you can't do this

$this->inst = new Classname();
echo $this->inst::someconstant;

but then why does this work?

$this->inst = new Classname();
$inst = $this->inst;
echo $inst::someconstant;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

From the PHP interactive shell:

php > class Foo { const A = 'a!'; }
php > class Bar { public $foo; }
php > $f = new Foo;
php > $b = new Bar;
php > $b->foo = $f;
php > echo $b->foo::A;
PHP Parse error:  syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM, expecting ',' or ';' in php shell code on line 1

The reason that the former syntax fails is that the PHP parser doesn't know how to resolve the double-colon after the property reference. Whether or not this is intentional is unknown.

The latter syntax works because it's not going through the property directly, but through a local variable, which the parser accepts as something it can work with:

php > $inst = $b->foo;
php > echo $inst::A;
a!

(Incidentally, this same restriction is in place for anonymous functions as properties. You can't call them directly using parens, you have to first assign them to another variable and then call them from there. This has been fixed in PHP's trunk, but I don't know if they also fixed the double colon syntax.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...