简体   繁体   中英

Is it possible to define a class property dynamically in php?

I have a class definition like:

class JConfig {
    var $offline = '0';
    var $editor = 'tinymce';
    var $list_limit = '20';
    var $helpurl = 'http://help.joomla.org';
    var $log_path = '/path/to/logs';
    // ....
}

I want to dynamically define '$log_path'

I've tried to define a constant outside the class declaration but no luck with that

Example:

if(!defined('ROOT_PATH')){
    define('ROOT_PATH', dirname(__FILE__));
}
class JConfig {
    var $offline = '0';
    var $editor = 'tinymce';
    var $list_limit = '20';
    var $helpurl = 'http://help.joomla.org';
    var $log_path = ROOT_PATH . '/logs'; // This generates a error
    // ....
}

But I cannot do that, is there a way to accomplish this?

You can do it in the class constructor

class JConfig {
    var $offline = '0';
    var $editor = 'tinymce';
    var $list_limit = '20';
    var $helpurl = 'http://help.joomla.org';
    var $log_path;

    public function __construct(){
        $this->log_path = ROOT_PATH . '/logs';
    }
}

No, you can't use constants or variables in your class property default values. I suggest you just set them in the constructor...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM