Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting class constants after constructor?

Tags:

oop

php

class

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 has 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();
   }
}
like image 716
Ali Avatar asked Mar 22 '11 09:03

Ali


1 Answers

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.

like image 144
Stefan Gehrig Avatar answered Oct 02 '22 02:10

Stefan Gehrig