Paolo
Paolo

Reputation: 19

PHP properties overloading

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

Upvotes: 0

Views: 54

Answers (3)

Mateusz Odelga
Mateusz Odelga

Reputation: 354

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

Upvotes: 1

user399666
user399666

Reputation: 19879

Make them protected instead of private.

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

Upvotes: 1

Machavity
Machavity

Reputation: 31614

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

Upvotes: 3

Related Questions