|
Posted by Matthew Weier O'Phinney on 08/04/05 22:49
* Marcus Bointon <marcus@synchromedia.co.uk>:
> 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 {}
> const BAR = 100;
> private $thing = self::BAR;
> function wibble($a = self::BAR) {
> echo $a;
> }
> }
>
> In this case $this->thing will be undefined, but wibble() will get
> the correct default value for $a.
>
> Comments?
This has been the case since PHP4. From http://php.net/oop:
In PHP 4, only constant initializers for var variables are allowed. To
initialize variables with non-constant values, you need an
initialization function which is called automatically when an object is
being constructed from the class.
What is meant by 'constant initializers' is that you cannot define class
variables based on variables, constants, or globals -- defined in the
class or otherwise. So, the following is okay:
private $thing = 100;
But, as you saw, the following will barf:
private $thing = self::BAR;
private $thing = BAR;
private $thing = $_SERVER['SCRIPT_NAME'];
// etc.
So, in other words, the issues you're seeing are consistent with the
documentation.
--
Matthew Weier O'Phinney
Zend Certified Engineer
http://weierophinney.net/matthew/
[Back to original message]
|