declaring private variable in class [message #175690] |
Thu, 20 October 2011 20:56 |
DavidB
Messages: 2 Registered: October 2011
Karma: 0
|
Junior Member |
|
|
Hi:
I created a class and then declared a private variable called today and set it = to today's date:
class someclass
{
private $today = date("Y-m-d");
}
For some reason, it doesn't like it. There is an error message about the parenthesis. Am I not allowed to set a variable = to some function like date or whatever? It didn't complain when I set it = to some string constant like "2011-10-10".
|
|
|
Re: declaring private variable in class [message #175691 is a reply to message #175690] |
Thu, 20 October 2011 21:20 |
Gregor Kofler
Messages: 69 Registered: September 2010
Karma: 0
|
Member |
|
|
Am 2011-10-20 22:56, DavidB meinte:
> Hi:
>
> I created a class and then declared a private variable called today and set it = to today's date:
>
> class someclass
> {
> private $today = date("Y-m-d");
> }
>
> For some reason, it doesn't like it. There is an error message about the parenthesis. Am I not allowed to set a variable = to some function like date or whatever? It didn't complain when I set it = to some string constant like "2011-10-10".
RTFM.
"This declaration may include an initialization, but this initialization
must be a constant value--that is, it must be able to be evaluated at
compile time and must not depend on run-time information in order to be
evaluated"
http://www.php.net/manual/en/language.oop5.properties.php
HTH, Gregor
|
|
|
Re: declaring private variable in class [message #175692 is a reply to message #175691] |
Thu, 20 October 2011 22:29 |
Robert Heller
Messages: 60 Registered: December 2010
Karma: 0
|
Member |
|
|
At Thu, 20 Oct 2011 23:20:08 +0200 Gregor Kofler <usenet(at)gregorkofler(dot)com> wrote:
>
> Am 2011-10-20 22:56, DavidB meinte:
>> Hi:
>>
>> I created a class and then declared a private variable called today and set it = to today's date:
>>
>> class someclass
>> {
>> private $today = date("Y-m-d");
>> }
>>
>> For some reason, it doesn't like it. There is an error message about the parenthesis. Am I not allowed to set a variable = to some function like date or whatever? It didn't complain when I set it = to some string constant like "2011-10-10".
>
> RTFM.
>
> "This declaration may include an initialization, but this initialization
> must be a constant value--that is, it must be able to be evaluated at
> compile time and must not depend on run-time information in order to be
> evaluated"
>
> http://www.php.net/manual/en/language.oop5.properties.php
In other words, you need to write a constructor method, which in turn
can initialize the private variable to a computed value. It is one of
the things constructor methods are for.
>
>
> HTH, Gregor
>
--
Robert Heller -- 978-544-6933 / heller(at)deepsoft(dot)com
Deepwoods Software -- http://www.deepsoft.com/
() ascii ribbon campaign -- against html e-mail
/\ www.asciiribbon.org -- against proprietary attachments
|
|
|