简体   繁体   English

是否可以在php中动态定义类属性?

[英]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' 我想动态定义'$ 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... 我建议您只在构造函数中设置它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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