PHP属性重载


PHP properties overloading

下面的代码有什么问题?

$inFile和$outFile总是由machine1而不是machine2初始化,这意味着在machine2的实例中,machine1的配置被打开(并写入)。

我做错了什么?我理解$this->somevar指的是实际实例化的对象(machine2)。

谢谢。

class machine1
{
    private  $inFile = "Config.ini";
    private  $outFile = "Config.web";
    
    public $fileArray = array();
    
    
    public function LoadData()
    {
        $handle = fopen(paths::$inifiles . $this->inFile,"r");
        // Read the file
        fclose($handle);
    }
    
    public function SaveData()
    {
        $handle = fopen(paths::$inifiles . $this->outFile,"w");
        //write the file
        fclose($handle);
    }
}
class machine2 extends machine1
{
    private  $inFile = "Config_1.ini";
    private  $outFile = "Config_1.web";
}
$obj = new machine2();
$obj->LoadData();
$obj->SaveData();

您使用private作为变量。这意味着子类不能继承、使用或重新定义它们。

试着把它们改成protected,我敢打赌它是有效的。你可以阅读更多关于他们在这个线程:https://stackoverflow.com/a/4361582/2370483

让它们受保护,而不是私有。

protected $inFile = "Config.ini";
protected $outFile = "Config.web";

最好的解决方案应该是使用构造函数初始化这些变量。如

in machine1:
public function __construct($inFile="Config.ini",$outFile="Config.web"){
    $this->inFile= $inFile;
    $this->outFile= $outFile;
}
in machine2:
public function __construct(){
    parent::__construct("Config_1.ini","Config1.web");
}