|
Posted by Dikkie Dik on 09/17/05 15:23
I think you get the compile time errors because the class properties can
be initialized with a constant expression only. Calling a function or
another variable is not seen as a constant expression, even if the
result is a constant.
This is a language thing, so I think you will have to live with it.
What you can do is creating some "root" instance of your class and set
the properties in the constructor. This also has the advantage of a more
testable object model.
Best regards
www.douglassdavis.com wrote:
> raf wrote:
>
>>www.douglassdavis.com wrote:
>>
>>>All three of the following classes give "compile-time" errors. It
>>>hinders me from doing what I want to do... And it seems there is no way
>>>around it. But, are each of these cases examples of how the language
>>>should behave? Are any of the examples a case of PHP being
>>>"incorrect?"
>>
>>I don't know PHP, but I believe these are bugs in your code:
>>
>>
>>
>>>class MyClass
>>>{
>>> static $x = 2;
>>> static $y = self::$x; // error
>>>}
>>
>>there is no instantiation of the class--there is no "self" object.
>>Did you mean "static $y = $x"?
>
>
> self:: isn't $this-> self:: just refers to the current class, just
> like putting the class name there. In PHP, you always have to prefix a
> class variable with something, even if you are writing code in that
> class.
>
>
>
>>>class MyClass2
>>>{
>>> var $x = 2;
>>> static $y = $x; // error
>>>}
>>
>>In this case, since no object was created, there is no $x to assign into
>> $y.
>>
>
>
> yes... this one doesn't make sense.
>
>
>>>class MyClass3
>>>{
>>> const a = array(1,2); // error
>>>}
>>
>>I defer this to someone who knows PHP, but if its semantics are
>>comparable to Java and C#, does "array(1,2)" actually create an instance
>>of an array? Based on the pattern of the errors above, I'd suggest you
>>review the concepts of object instantiation and class/instance member
>>variables.
>
>
> yes array creates an instance of array.
>
>
> to the PHP folks out there:
>
> My delima is this... let's say you wanted to do something like this in
> a class, and you needed all 3 of these vars to be defined.
>
> class MyClass4
> {
> var $one = array(1,2);
> var $two = array(3,4);
> var $three= array($one, $two); // a two dimensional array.
> // ... more code below
> }
>
> But you knew that these would always remain the same, and there was no
> need for putting them in every class. Meaning, if they are not static,
> it's just a waste of space.
>
> Also, there are no static initializer blocks like java.
>
> Is there a correct way to define this in the class this without wasting
> space?
>
[Back to original message]
|