简体   繁体   English

从常量类文件中访问常量

[英]accessing constant from within constant class file

    class Constants
    {
            public static $url1      = "http=//url1";
            public static $url2       = Constants::$url1."/abc";
    }

I want to access constant from with in a class but i am not able yo do it. 我想从一个类中的with中访问常量,但是我不行。 How can i do it ? 我该怎么做 ?

Instead of using Constants:: you should use self:: to access class variables. 而不是使用Constants::您应该使用self::访问类变量。 For example: 例如:

public static $url2 = self::$url1 . "/abc";

This is not a constant. 这不是一个常数。 This is a static property. 这是一个静态属性。

You also cannot use self as value: 您也不能将self作为价值:

public static $url2 = self::$url1."/abc"; // will throw error

You have to initialize in constructor: 您必须在构造函数中进行初始化:

class Constants
{
    public static $url1 = "http=//url1";
    public static $url2;

    public function __construct(){
        self::$url2 = self::$url1."/abc";
    }
}

$const = new Constants();
echo $const::$url2;
//or if the class is initialized
echo Constants::$url2;

The other option would be to make a static method: 另一个选择是制作一个静态方法:

class Constants
{
    public static $url1 = "http=//url1";        

    public static function getUrl2(){
        return self::$url1."/abc";
    }
}

echo Constants::getUrl2();

Just see Below Codes. 请参阅下面的代码。

From outside the class definition 从类定义之外

    <?php
    class MyClass {
        const CONST_VALUE = 'A constant value';
    }

    $classname = 'MyClass';
    echo $classname::CONST_VALUE; // As of PHP 5.3.0

    echo MyClass::CONST_VALUE;
    ?>

From inside the class definition 从类定义内部

    <?php
    class OtherClass extends MyClass
    {
        public static $my_static = 'static var';

        public static function doubleColon() {
            echo parent::CONST_VALUE . "\n";
            echo self::$my_static . "\n";
        }
    }

    $classname = 'OtherClass';
    echo $classname::doubleColon(); // As of PHP 5.3.0

    OtherClass::doubleColon();
    ?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM