Re: [PHP] class as default property

2008-06-23 Thread Stut

On 23 Jun 2008, at 09:36, Osman A. Osman (عثمان) wrote:

I had a quick question.  How come I can do this:
?php
class Foo {
}
class Bar {
 public $f = 'SomeFoo';
}
?

But this does not work:
?php
class Foo {
}
class Bar {
 public $f = new Foo();
}
?
*(Parse error: syntax error, unexpected T_NEW in test.php on line 8)*
**


Those assignments are evaluated at compile-time when no code can be  
executed. As such it is only possible to set them to literal values.


If you need to set the default value of member variables to new  
objects the place to do it is the constructor.


-Stut

--
http://stut.net/


--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



RE: [PHP] class as default property

2008-06-23 Thread Chetan Rane
You can use a contructor in this case
?php
class Foo {
}
class Bar {
function __construct() {
public $f = 'SomeFoo';
}
}
?
But this does not work:
?php
class Foo {
}
class Bar {
function __construct() {
public $f = new Foo();  
}
}
?


Chetan Dattaram Rane | Software Engineer | Persistent Systems
[EMAIL PROTECTED]  | Cell: +91 94033 66714 | Tel: +91 (0832) 30 79014
Innovation in software product design, development and delivery- 
www.persistentsys.com



-Original Message-
From: Stut [mailto:[EMAIL PROTECTED] 
Sent: Monday, June 23, 2008 2:21 PM
To: Osman A. Osman (عثمان)
Cc: php-general@lists.php.net
Subject: Re: [PHP] class as default property

On 23 Jun 2008, at 09:36, Osman A. Osman (عثمان) wrote:
 I had a quick question.  How come I can do this:
 ?php
 class Foo {
 }
 class Bar {
  public $f = 'SomeFoo';
 }
 ?

 But this does not work:
 ?php
 class Foo {
 }
 class Bar {
  public $f = new Foo();
 }
 ?
 *(Parse error: syntax error, unexpected T_NEW in test.php on line 8)*
 **

Those assignments are evaluated at compile-time when no code can be  
executed. As such it is only possible to set them to literal values.

If you need to set the default value of member variables to new  
objects the place to do it is the constructor.

-Stut

-- 
http://stut.net/


-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php