Cesar
Cesar

Reputation: 4116

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?

Upvotes: 2

Views: 615

Answers (2)

Yacoby
Yacoby

Reputation: 55445

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';
    }
}

Upvotes: 5

Franz
Franz

Reputation: 11553

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

Upvotes: 1

Related Questions