Home arrow PHP arrow Page 4 - Defining Public and Protected Methods with Member Visibility in PHP 5

Calling protected methods from a subclass - PHP

In the previous articles of this series, I explained how to work with public and protected class properties. So now itís time to demonstrate how to specify these same levels of visibility in the respective methods of a class. Sounds pretty interesting, right?

TABLE OF CONTENTS:
  1. Defining Public and Protected Methods with Member Visibility in PHP 5
  2. Calling methods of a class globally
  3. Declaring and implementing protected methods within PHP 5 classes
  4. Calling protected methods from a subclass
By: Alejandro Gervasio
Rating: starstarstarstarstar / 2
June 11, 2008

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement


Before you finish this article, I'd like to show you a final educational example to illustrate what occurs when the protected methods of the previous "DataSaver" class are accessed by one of its subclasses.

To recreate this particular scenario, I'm going to create the mentioned subclass, as indicated below:


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

protected function getFilePath(){

return $this->filePath;

}

// get data via an accessor

protected function getData(){

return $this->data;

}

}


// extends 'DataSaver' class

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;

}

// fetch all data

public function getAllData(){

return 'Target File: '.$this->getfilePath().' Data: '.$this->getData();

}

}


I simply retrieved a basic subclass, called "DataHandler," from the pertinent "DataSaver" parent to expand its existing functionality. However, apart from grasping how the sub classing process functions, I'd like you to pay attention to a brand new method, named "getAllData()," that is defined by the child class.

As you can see, this method returns the values of the respective $data and $filePath properties to client code by using two protected methods ("getFilePath()" and "getData()") implemented by the corresponding base class.

In theory, it would be perfectly possible to call the "getAllData()" method without getting any fatal errors, since the pertinent protected methods are invoked from inside the child class. But in practice, would it be possible? Of course, this can be done!

And to demonstrate the veracity of this concept, below I coded a short script that shows how the protected methods in question are seamlessly called via the  "getAllData()" method. Here's the corresponding code sample:


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

// call protected methods

echo $dataHandler->getAllData();

 

/* displays the following

Target File: datafile.txt Data: This string of data will be saved to a target file!

*/

}

catch(Exception $e){

echo $e->getMessage();

exit();

}


Even though the above script looks pretty simplistic, it does demonstrate how two protected methods defined by a parent class can also be called from inside an eventual subclass. Of course, as with many other topics related to PHP 5 web development, the best way to acquire a solid background in working with protected methods is through practice.

Final thoughts

In this fourth chapter of the series, I provided you with an introductory guide on how to declare and implement public and protected methods within PHP 5 classes. As you saw, the topic is quite simple to grasp, so I guess you shouldn't have major problems mastering its basic concepts.

In the next part, I'll be explaining the use of private methods in PHP 5. If you're interested in learning how to increase the level of restriction for the methods of your PHP 5 classes, then you simply can't miss this article!



 
 
>>> More PHP Articles          >>> More By Alejandro Gervasio
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: