将静态变量的值分配给类变量


Assigning value of static variable to a class variable

Config.php

class Config {
    public static $dbserver = "hostedserverURL";
}

数据库.php

require 'Config.php'
class DB {
    private $server =  Config::$dbserver; // compile-error
    private $user = "user";
    private $password =  "password";
    private $database =  "databasename";
    private $db;
}

编译错误说"syntax error, unexpected '$dbserver', expecting 'identifier' or 'class'"

如果我删除$并将行更改为private $server = Config::dbserver;,则编译错误消失了。 但这是不正确的。在这种情况下,我收到运行时错误。 Fatal error: Undefined class constant 'Config::dbserver' in ..

所以我必须保留$,也按照这个SO线程: 致命错误:未定义的类常量

这就是我使用它的地方,

public function __construct()
    {
        $this->db = new PDO(
            "mysql:host={$this->server};dbname={$this->database};charset=utf8",
            $this->user,
            $this->password
        );
        return $this;
    }

问题:如何将静态变量引用dbserver并将其作为class DB $server的默认值?请有任何想法

在 5.6 之前,您不能从函数和其他类或非平凡表达式中分配类中的变量。 您必须使用类中的函数设置变量。

现在,在终端中输入php -v以查看您正在使用的版本。 否则,如果要使用该功能,请将 PHP 升级到 PHP 5.6

https://wiki.php.net/rfc/const_scalar_exprs

这是一个 php(版本 <5.6)限制,但是您可以简单地初始化构造函数中的属性:

class DB 
{
    private $server;
    private $user;
    private $password;
    private $database;
    private $db;
    public function __construct()
    {
        $this->server   = Config::$dbserver; // No compile-error
        $this->user     = "user";
        $this->password = "password";
        $this->database = "databasename";
        $this->db       = new PDO(
            "mysql:host={$this->server};dbname={$this->database};charset=utf8",
            $this->user,
            $this->password
        );
        //return $this; no need for this
    }
}

或者升级到更高 (5.6+) 版本的 php。

此外,从设计的角度来看,将各种变量硬编码并分散在 2 个文件中非常复杂。理想情况下,将它们全部注入到构造函数中:

public function__construct($server, $user, $password, $database)
{
    $this->server = $server; 
    $this->user   = $user;
    //etc
} 

如果失败,则它们都在 config 类中声明:

public function__construct()
{
    $this->server = Config::$server; 
    $this->user   = Config::$user;
    //etc
} 

不能使用类外部的变量,即使在同一文件中需要它们。

你可以这样做:

class DB {
    private $server;
    private $user = "user";
    private $password =  "password";
    private $database =  "databasename";
    private $db;  
    public function __construct(){
       require 'Config.php';
       $this->server = Config::$dbserver; //Will set the $server variable of the instantiated class.
    }
}