Can you use static constants in PHP?

后端 未结 6 1045
面向向阳花
面向向阳花 2021-02-01 12:55

I expected the following to work but it doesn\'t seem to.



        
相关标签:
6条回答
  • 2021-02-01 12:57

    Nope class constants can't be labeled static nor assigned visibility.

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

    0 讨论(0)
  • 2021-02-01 12:59

    In PHP, static and const are two different things.

    const denotes a class constant. They're different than normal variables as they don't have the '$' in front of them, and can't have any visibility modifiers (public, protected, private) before them. Their syntax:

    class Test
    {
        const INT = "/^\d+$/";
    }
    

    Because they're constant, they're immutable.

    Static denotes data that is shared between objects of the same class. This data can be modified. An example would be a class that keeps track of how many instances are in play at any one time:

    class HowMany
    {
        private static $count = 0;
    
        public function __construct()
        {
            self::$count++;
        }
    
        public function getCount()
        {
            return self::$count;
        }
    
        public function __destruct()
        {
            self::$count--;
        }
    }
    
    $obj1 = new HowMany();
    $obj2 = new HowMany();
    
    echo $obj1->getCount();
    
    unset($obj2);
    
    echo $obj1->getCount();
    
    0 讨论(0)
  • 2021-02-01 12:59

    You don't need to declare them static or public. Check out the examples in the manual:

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

    0 讨论(0)
  • 2021-02-01 13:05

    How are you trying to access the constants?

    I believe this would work:

    echo Patterns::$EMAIL; //shows "/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-...."
    

    If you just declare it as static.

    0 讨论(0)
  • 2021-02-01 13:17

    You can use const in class like this:

    class Patterns {
        const EMAIL = "/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix";
        const INT = "/^\d+$/";
        const USERNAME = "/^\w+$/";
    }
    

    And can access USERNAME const like this:

    Patterns::USERNAME
    
    0 讨论(0)
  • 2021-02-01 13:19

    They're not static constants, just constants

    class Patterns 
    { 
        const EMAIL = "/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix"; 
        const INT = "/^\d+$/"; 
        const USERNAME = "/^\w+$/"; 
    } 
    
    echo Patterns::EMAIL;
    
    0 讨论(0)
提交回复
热议问题