Re: Class constants

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

 



* Marcus Bointon <marcus@xxxxxxxxxxxxxxxxxx>:
> 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/

-- 
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