Accessing PHP Class Constants

前端 未结 4 1035
谎友^
谎友^ 2020-12-14 19:14

The PHP manual says

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

which explains wh

相关标签:
4条回答
  • 2020-12-14 19:35

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

    0 讨论(0)
  • 2020-12-14 19:44

    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.

    0 讨论(0)
  • 2020-12-14 19:48

    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

    0 讨论(0)
  • 2020-12-14 19:52

    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 讨论(0)
提交回复
热议问题