You are here: Re: [PHP] Class constants « PHP « IT news, forums, messages
Re: [PHP] Class constants

Posted by Jochem Maas on 11/13/59 11:22

Marcus Bointon wrote:
> I'm not sure if this is a bug or a feature, but it seems you can't use
> class constants to set default values for class properties. You can,
> however, use them for default values for method params, e.g.:
>
> class foo {}
^--- er.

> const BAR = 100;
> private $thing = self::BAR;
> function wibble($a = self::BAR) {
> echo $a;
> }
> }

class foo {
const BAR = 100;
private $thing = self::BAR;
function wibble($a = self::BAR) {
echo $a;
}
}
$f = new foo;
$f->wibble();

it _seems_ you did not test this, at least when I run this it gives me a fatal error
(which definitely leaves $this->thing undefined!)

>
> In this case $this->thing will be undefined, but wibble() will get the
> correct default value for $a.
>
> Comments?

I believe this is due to the fact that when setting up $thing, php is still building
the class definition therefore the constant does not 'exist' yet. the error msg I get
seems to confirm this.

this does work:

class qux { const BAR = 100; }
class foo {
const BAR = 100;
private $thing = qux::BAR;
function wibble($a = self::BAR) {
echo $a,"\n",$this->thing;
}
}
$f = new foo;
$f->wibble();


this does work, which really surprised me.


class foo {
const BAR = 100;
private $thing = foo::BAR;
function wibble($a = self::BAR) {
echo $a,"\n",$this->thing;
}
}
$f = new foo;
$f->wibble();


but honestly if you want to be very stricly correct about you OO then you
should not (I believe) be setting a value to an instance member in the class
definition, instead do:

class foo {
const BAR = 100;
function __construct() {
$this->thing = self::BAR;
}
function wibble($a = self::BAR) {
echo $a,"\n",$this->thing;
}
}
$f = new foo;
$f->wibble();



I tested all this on PHP 5.0.2 (cli) (built: Oct 21 2004 13:52:27)

>
> Marcus

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация