While making the static class for database getting this error

后端 未结 4 2115
鱼传尺愫
鱼传尺愫 2020-12-22 10:05

Here is my class

class Databases {
    public $liveresellerdb = new Database(\'1host1\',\'user\',\'pswd\',\'db\');
}

the error i am gettin

相关标签:
4条回答
  • 2020-12-22 10:33
    <?php
    
    class Databases {
        public static $liveresellerdb;
    }
    Databases::$liveresellerdb = new Database('1host1','user','pswd','db');
    
    ?>
    

    This is how you initialise a static member...

    0 讨论(0)
  • 2020-12-22 10:43

    Because you forgot to write the static keyword to actually make the property static.

    In addition, you can't initialise static properties with expressions like this. Here's a workaround.

    0 讨论(0)
  • 2020-12-22 10:46

    Properties may not be preset with runtime information.

    Quoting PHP Manual:

    Class member variables are called "properties". You may also see them referred to using other terms such as "attributes" or "fields", but for the purposes of this reference we will use "properties". They are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration. This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

    0 讨论(0)
  • 2020-12-22 10:47

    you cannot assign object during the class preperation stages, only the class instantation:

    class Databases
    {
        public $liveresellerdb;
    
        public function __construct()
        {
            $this->liveresellerdb = new Database('1host1','user','pswd','db');
        }
    }
    

    anything within the constructor can be generic PHP code, outside the function and instead the class body has specific laws.

    if you require the database's to be static then you have to set / access them differently.

    class Databases
    {
        public static $liveresellerdb;
    }
    
    Databases::liversellerdb = new Database('1host1','user','pswd','db');
    
    0 讨论(0)
提交回复
热议问题