开发者

Setting class constants after constructor?

I have a class with the following schema

class MyClass
{
   const x = 'abc';
   const y = '123';

   function _contruct() {}
}

Is there any way for me to have the constants remain unset in the class body, and be set dynamically after the constructor ha开发者_开发技巧s been called? E.g something like this:

class MyClass
{
   const x;
   const y;

   function _contruct()
   {
      $this->setStuff();
   }

   function setStuff()
   {
     $this->x = Config::getX();
     $this->y = Config::getY();
   }
}


As the name suggests, that value cannot change during the execution of the script (except for magic constants, which aren't actually constants) (http://php.net/manual/en/language.constants.php)

So, no. You could make them private vars.


No. Class constants (and global or namespace constants defined with the const keyword) have to be literal values and must be set prior to runtime. That's where they differ from the old-school define() constants that are set at runtime. It's not possible to change or set a const constant during the execution of a script.

The value must be a constant expression, not (for example) a variable, a property, a result of a mathematical operation, or a function call.

from PHP manual: Class Constants

So that's possible:

define('MY_CONST', someFunctionThatReturnsAValue());

But that's not:

const MY_CONST = someFunctionThatReturnsAValue();

// or

class MyClass {
    const MY_CONST = = someFunctionThatReturnsAValue();
}

// or

namespace MyNamespace;
const MY_CONST = someFunctionThatReturnsAValue();

And by using $this in your example one might assume that you try to set the constants on the instance level but class constants are always statically defined on the class level.


No, constants are constants because they are supposed to be constant. Declaring them with empty values first and changing those values with something else effectively means they are variable. Since your aim seems to be to set them once, but not ever after, consider Constructor Injection, e.g.

class MyClass
{
    private $x;
    private $y;
    public function __construct($x, $y)
    {
        $this->x = $x;
        $this->y = $y;
    }
}

As long as your class doesnt expose any methods to modify $x and $y and you're not chaning them internally, they are effectively constant. The only thing you cannot do with non-public variables is MyClass::X then, but I'm of the opinion that you shouldn't use class constants outside their respective classes anyway because it introduces coupling between the consumer and the class.

Simple as that.


Constants is "constant". You cant change it.

You can use variable for this.


Impossible. If you could set x and y in setStuff(), you could also (re-)set them in any other method. Per definition a constant cannot change. Therefore your x and y would be variables, not constants.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜