Re: Class constants

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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

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


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux