i wanna store some configuration data in some objects, and i’ve a problem…
class B {
const attr1 = 'something1';
const attr2 = 'something2';
const attr3 = 'something3';
}
class A {
const attr1 = 'somethingA1';
const attr2 = 'somethingA2';
const attr3 = 'somethingA3';
const b = <---- i wanna put here a reference of B, but B as a class (not an object...), i'm crazy?
}
I’m not sure if my example is clear… from A, i want to access to attr1 of B, like A::B::attr1, or something like this, there’s another way to do this? Or i’m wrong?
There is no way to assign reference to a Class, nor is there a way to assign class constants at runtime. So your entire approach is pretty much impossible. What you can do is
and as of PHP 5.3.0 you could then do
but you cannot do
A::b::attr1. This will raise aT_PAAMAYIM_NEKUDOTAYIMerror. It’s a parser limitation. PHP cannot do this as of this writing.You can solve this easily by making
Ba composite ofA, e.g. you either injectBintoAwhen you createAor create
BinsideA, e.g.Because
Bis just the data parts ofA, you tunnel all public access throughAinstead of getting hold ofBand then using B’s methods. So any code usingAdoes not need to know there is someBinsideA. This will allow you to changeBeasily without needing to worry about code that consumesA, e.g. to getattr1you add a getter toA:You can mitigate the clumsy need for assignment when using properties instead of constants in
B(constants are stupid in PHP anyway as you have to treat them as public API), e.g.And then you can do in
A:Even better would be not to expose the internals of
BthroughAaltogether though and only add public methods that do something with A. This will make your API much smaller and your code more OO.