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();

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

1

Make them protected instead of private.

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

Comments

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");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.