As I explained in the prior section, the properties of a class that have been declared protected can be accessed freely by any subclass derived from the corresponding parent. In order to demonstrate this concept, below I coded a basic example that shows how the protected properties of the previous “DataSaver” class can be retrieved by a subclass. Here’s the code sample; examine it in detail, please: class DataSaver{ protected $filePath; protected $data; public function __construct($data,$filePath){ if(!$data||strlen($data)>1024){ throw new Exception('Invalid data for being saved to target file.'); } if(!file_exists($filePath)){ throw new Exception('Invalid target file.'); } $this->data=$data; $this->filePath=$filePath; } // save data to target file public function save(){ if(!$fp=fopen($this->filePath,'w')){ throw new Exception('Error opening target file.'); } if(!fwrite($fp,$this->data)){ throw new Exception('Error writing data to target file.'); } fclose($fp); } // get target file via an accessor public function getFilePath(){ return $this->filePath; } // get data via an accessor public function getData(){ return $this->data; } } // extends 'DataSaver' class and try to access protected properties class DataHandler extends DataSaver{ // fetch data from target file public function fetch(){ if(!$data=file_get_contents($this->filePath)){ throw new Exception('Error reading data from target file.'); } return $data; } } try{ // create new instance of 'DataHandler' class $dataHandler=new DataHandler('This string of data will be saved to a target file!','datafile.txt'); // save data to target file $dataHandler->save(); // fetch data from target file echo $dataHandler->fetch();
/* displays the following This string of data will be saved to a target file! */ } catch(Exception $e){ echo $e->getMessage(); exit(); } Now things are getting really interesting! As you can see, first, I derived a simple subclass from the pertinent “DataSaver” parent, and then used the brand new “fetch()” method to access the protected “$filePath” property. In doing so, I’m demonstrating how a protected property can be retrieved from inside a child class. Quite simple to understand, right? All right, at this stage you've hopefully learned how to get access to a pair of protected properties defined by a parent using a child class. So the question is: what comes next? Well, as I said in the beginning of this article, PHP 5 supports the definition of private properties via the “private” keyword. Thus, in the section to come, I’m going to teach you how to work with properties that have that specific level of visibility. Naturally, in order to learn more about this useful topic, you’ll have to click on the link below and keep reading.
blog comments powered by Disqus |
|
|
|
|
|
|
|