0

I am new to the community. I would like to ask a question: How would I add a constant to another class? So here is my class that contains the constant:

class MyClass1 {
    const CONSTANT_FOO;
}

And this is the class that will add a new constant to class MyClass1:

class MyClass2 {
    //what would I put here?
}
3
  • does MyClass1 extend MyClass2, or vice versa? Commented Sep 2, 2016 at 13:58
  • 3
    why would you try to modify a constant? constants are constant ;) . they shouldn't be modified at runtime. Commented Sep 2, 2016 at 14:06
  • 1
    Why do you need to define the same constant in every class; just put in a single (appropriate) class and you can then reference it everywhere in your code as MyClass1::CONSTANT_FOO.... and note that you should be setting a value in your constant definition Commented Sep 2, 2016 at 14:08

2 Answers 2

1

How would I add a Constant to another class?

The short answer: you cannot add a constant to another class.

However, the constants, as their name says, are just names for values that do not change during the execution of the program. This is probably the reason they are all public and their visibility cannot be restricted.

All of them being public, the only difference between the global constants created using define() and class constants is the syntax on creation and access.

The complete answer to your question is: you cannot add a constant to a class during runtime (from the code of another class or even from the code of the class itself) but you also don't need it. It's enough to define() a constant or declare it as const in another class.

The only way to add a constant to a class is to modify the definition of the class (using an editor, of course).

Sign up to request clarification or add additional context in comments.

Comments

0

Constants are something which shouldn't be modified at run time. As the name says, this is meant to be a CONSTANT. You can achieve the same using class variable.

  1. Declare a class variable in MyClass1.
  2. Instantiate MyClass1 in MyClass2.
  3. Set the required value to the variable in the created object.
  4. You can use this object further which actually has the value you have assigned.

To make it better, you can have setter and getter methods in MyClass1 or use magic methods in PHP.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.