开发者

Accessing PHP Class Constants

The PHP manual says

Like static members, constant values can not be accessed from a开发者_StackOverflow社区n 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;


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.)


If you are within the class, you can access the constant like this:

self::MY_CONSTANT;

For example:

class MyClass {
    const MY_CONSTANT = 'constant value';

    public function showConstant() {
        echo self::MY_CONSTANT;
    }
}

http://php.net/manual/en/language.oop5.constants.php


To quote the manual:

As of PHP 5.3.0, it's possible to reference the class using a variable. The variable's value can not be a keyword (e.g. self, parent and static).

It goes on to use this example:

$class = new MyClass();
echo $class::constant."\n"; // As of PHP 5.3.0

So $inst::someconstant is supposed to work.

As to why $this->inst::someconstant gives a parsing error, I don't know. PHP is funny about some things.


php supports accessing class constants from an object instance. Code below is working (checked in phpv5.5.5):

<?php
class superheroes{
    const kal_el = 'Superman';
}

$instance = new superheroes;
echo $instance::kal_el;

Source: http://dwellupper.io/post/48/defining-class-constants-in-php

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜