0

What's wrong with the following code?

$inFile and $outFile get initialized ALWAYS by machine1 and not by machine2, which means that with an instance of machine2 the config of machine1 gets opened (and written).

What am I doing wrong? I understood that $this->somevar refers to the object actually instantiated (machine2).

Thanks.

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();
Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Paolo
  • 19
  • 4

3 Answers3

3

You're using private for the variables. That means that child classes cannot inherit them, use them, or redefine them.

Try changing them to protected and I bet it works. You can read more about them in this thread: https://stackoverflow.com/a/4361582/2370483

Community
  • 1
  • 1
Machavity
  • 30,841
  • 27
  • 92
  • 100
1

Make them protected instead of private.

protected $inFile = "Config.ini";
protected $outFile = "Config.web";
Wayne Whitty
  • 19,513
  • 7
  • 44
  • 66
1

The best solution should be initializing those variables using constructor. e.g

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");
}
Mateusz Odelga
  • 354
  • 2
  • 7